Android圆角ImageView的几种实现方式(包含四个角的分别设置)

在实际的开发中,我们经常会遇到需要圆角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,
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

chailongger

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值