三种方式实现圆角或圆形图片的自定义View

本文介绍了开发中实现圆角或圆形图片的三种常见方式:使用Xfermode混合图层、BitmapShader以及通过ClipPath裁剪画布。详细讲解了自定义View的过程,包括属性、构造函数、onMeasure、onDraw等关键步骤,并提供了Glide4.0的实现配置。文章旨在帮助读者理解自定义View的基本过程。
摘要由CSDN通过智能技术生成

前言
实现圆角或圆形图片显示,我们开发中除了把原图直接做成圆角外,常见有三种方式实现:
使用Xfermode混合图层;
使用BitmapShader;
通过裁剪画布区域实现指定形状的图形(ClipPath)。
今天我就来带大家通过上面三种方式实现圆角或圆形的自定义View。

先来张效果图:
在这里插入图片描述

实现
1. 自定义属性

    <attr name="borderRadius" format="dimension" />
    <attr name="type">
        <enum name="circle" value="0" />
        <enum name="round" value="1" />
    </attr>
    <attr name="src" format="reference"/>
    <declare-styleable name="XfermodeCircleView">
        <attr name="borderRadius" />
        <attr name="type" />
        <attr name="src" />
    </declare-styleable>

属性说明:
type: 圆角或圆形
src: 图片资源Id(这里使用的资源图片作为案例)
borderRadius: 圆角半径大小

2. 自定义View
我这里自定义了三个View, 大部分代码一致的,就是在onDraw方法实现不一样, 所以我这里就不重复贴出来了。
XfermodeCircleView、ClipPathCircleView 继承的View
BitmapShaderView 继承的ImageView

属性

    private static final int TYPE_CIRCLE = 0;
    private static final int TYPE_ROUND = 1;

    private int mRadius;                //半径大小
    private int mBorderRadius;          //圆角大小
    private int mWidth, mHeight;        //控件宽高
    private int mType;                  //圆角还是圆
    private RectF mRoundRect;           // 圆角矩阵
    private BitmapShader mBitmapShader; //Shader
    private Paint mBitmapPaint;         //图片画笔
    private Matrix mMatrix;             //Bitmap缩放矩阵

构造函数

    public XfermodeCircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.XfermodeCircleView, defStyleAttr, 0);
        this.mSrc = BitmapFactory.decodeResource(getResources(), a.getResourceId(R.styleable.XfermodeCircleView_src, 0));
        this.mType = a.getInt(R.styleable.XfermodeCircleView_type, 0);
        this.mBorderRadius = a.getDimensionPixelSize(R.styleable.XfermodeCircleView_borderRadius, 10);
        a.recycle();
        init();
    }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值