在实际的开发中,我们经常会遇到需要圆角ImageView的情况,但是这种ImageView官方是没有提供的,所以需要我们去自己重写ImageView来达到圆角的效果,但是实现这种圆角效果其实有几种不同的实现方式,所以这一篇就对不同的实现方式进行讲解,并简单分析。
一.BitmapShader方式
首先简单了解下BitmapShader,BitmapShader是Shader的子类,Shader在三维软件中我们称之为着色器,所以通俗的理解,Shader的作用是给图像着色或者上色,BitmapShader允许我们载入一张图片来给图像着色,具体不做过多的解释,结尾贴出关于Shader的具体使用的文章
所以其实根据上面对于BitmapShader的描述,其实就可以对圆角ImageView有一定的思路了吧,画一个圆角矩形,然后把本来画上去的图像着色到圆角矩形上,这样就实现了圆角的ImageView
思路说了就把代码直接贴上来了,代码注释也很清楚的,不做过多的解释了
public class RoundImageView extends ImageView{
//圆角大小,默认为10
private int mBorderRadius = 10;
private Paint mPaint;
// 3x3 矩阵,主要用于缩小放大
private Matrix mMatrix;
//渲染图像,使用图像为绘制图形着色
private BitmapShader mBitmapShader;
public RoundImageView(Context context) {
this(context, null);
}
public RoundImageView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public RoundImageView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mMatrix = new Matrix();
mPaint = new Paint();
mPaint.setAntiAlias(true);
}
@Override
protected void onDraw(Canvas canvas) {
if (getDrawable() == null){
return;
}
Bitmap bitmap = drawableToBitamp(getDrawable());
mBitmapShader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
float scale = 1.0f;
if (!(bitmap.getWidth() == getWidth() && bitmap.getHeight() == getHeight()))
{
// 如果图片的宽或者高与view的宽高不匹配,计算出需要缩放的比例;缩放后的图片的宽高,一定要大于我们view的宽高;所以我们这里取大值;
scale = Math.max(getWidth() * 1.0f / bitmap.getWidth(),
getHeight() * 1.0f / bitmap.getHeight());
}
// shader的变换矩阵,我们这里主要用于放大或者缩小
mMatrix.setScale(scale, scale);
// 设置变换矩阵
mBitmapShader.setLocalMatrix(mMatrix);
// 设置shader
mPaint.setShader(mBitmapShader);
canvas.drawRoundRect(new RectF(0,0,getWidth(),getHeight()), mBorderRadius, mBorderRadius,

&spm=1001.2101.3001.5002&articleId=117000920&d=1&t=3&u=317bb1c33c6545e3abeaa02b94b74665)
5万+

被折叠的 条评论
为什么被折叠?



