自定义View之将图片裁剪成圆形图片

本文介绍了三种在Android中将图片裁剪成圆形的方法:1) 使用PorterDuffXfermode,需要开启硬件加速;2) 通过BitmapShader重新绘制,实现较复杂但可扩展性强;3) 利用clipPath直接裁剪,简单粗暴但无法处理图片。每种方式都有其优缺点,适用场景不同。
摘要由CSDN通过智能技术生成

自定义View之将图片裁剪成圆形图片

使用PorterDuffXfermode方式来实现

在使用这中方式之前,我们有必要弄清楚PorterBuddx究竟是什么。
简单来说,他是定义的一种图像融合的方式,具体的模式有如下几种,效果如图:
官方的说明图

在次,不多做介绍,想深入了解PorterDuffXfermode可以参考各个击破搞明白PorterDuff.Mode
本次使用mode是SRCIN,由图效果可知,我们需要在原图上绘制一个圆,原图与我们绘制得圆重叠得区域就会显示出来,原理很简单,下面开始代码实现:

public class CircleImageView1 extends ImageView {
   

    private Paint mPaint;
    private Shape mShape;
    private float mRadius;

    private float[] outerRadii = new float[8];;

    public CircleImageView1(Context context) {
        this(context,null);
    }

    public CircleImageView1(Context context, @Nullable AttributeSet attrs) {
        this(context,attrs,0);
    }

    public CircleImageView1(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        setLayerType(LAYER_TYPE_HARDWARE,null);
        mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        mPaint.setColor(Color.BLACK);
        //注意这里,将画笔的PorterDuffXfermode模式设置为了DST_IN模式!!!
        mPaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int width = getMeasuredWidth();
        int height = getMeasuredHeight();
        int min = Math.min(width,height);
        mRadius = min/2;
        setMeasuredDimension(min,min);
        //因为是圆,所以要设置为长宽相等
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed){
            if (mShape == 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值