自定义绘制圆形图片

 自定义绘制圆形图片_第1张图片

/**
 * Created by lz on 2018/10/29.
 * 功能描述: 自定义绘制圆形图片
 */

public class CircleImageView extends View {
    private static final float WIDTH = Utils.dp2px(300);
    private static final float PADDING = Utils.dp2px(50);
    private static final float EDGE_WIDTH = Utils.dp2px(10);

    Xfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN);
    private Bitmap mBitmap;
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    RectF saveArea = new RectF();
    public CircleImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }
    {
        mBitmap = getAvatar((int) WIDTH);
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        saveArea.set(PADDING,PADDING,PADDING+WIDTH,PADDING+WIDTH);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //canvas.drawOval(PADDING,PADDING,PADDING+WIDTH,PADDING+WIDTH,paint);
        //https://blog.csdn.net/cquwentao/article/details/51423371
        int saved = canvas.saveLayer(saveArea,paint);
        //canvas.drawOval(PADDING+EDGE_WIDTH,PADDING+EDGE_WIDTH,PADDING+WIDTH-EDGE_WIDTH,PADDING+WIDTH-EDGE_WIDTH,paint);
        canvas.drawOval(PADDING,PADDING,PADDING+WIDTH,PADDING+WIDTH,paint);
        paint.setXfermode(xfermode);
        canvas.drawBitmap(mBitmap,PADDING,PADDING,paint);
        paint.setXfermode(null);
        canvas.restoreToCount(saved);
    }

    Bitmap getAvatar(int width) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(getResources(), R.drawable.img, options);
        options.inJustDecodeBounds = false;
        options.inDensity = options.outWidth;
        options.inTargetDensity = width;
        return BitmapFactory.decodeResource(getResources(), R.drawable.img, options);
    }
}

你可能感兴趣的:(自定义控件)