Android——自定义图形。(Canvas,Paint,Bitmap,PorterXFermode)

简介

  Android自定义图形利用View里onDraw(Canvas canvas)方法,重新绘制图形。

 

  五步:

    1. getWidth() , getHeight():获取组件的宽和高

    2. 让背景变为白色  canvas.setRect(0,0,width,height,paint);

    3. 获取目标图片Bitmap:View.getDrawable();  drawable.drawCanvas(canvas)

    4. 获取想要形状的Bitmap:canvas.drawOval(0,0,width,height,paint)

    5. 保存图层,调用onDraw(Canvas canvas)里的canvas绘制两个Bitmap。src目标需要后绘制。恢复图层

 

使用

// 自定义圆形图片

public class MERoundImgView extends androidx.appcompat.widget.AppCompatImageView {
    private Bitmap dstImageViewBitmap;
    private Bitmap srcCircleBitmap;
    private Canvas dstCanvas;
    private Canvas srcCanvas;

    public MERoundImgView(Context context) {
        super(context);
    }

    public MERoundImgView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

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

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // 1.获取宽高,用于设置位图大小
        int width = getWidth();
        int height = getHeight();

        // 2.设置新白色图层
        Paint paint = new Paint();
        paint.setColor(Color.parseColor("#ffffff"));
        canvas.drawRect(0,0,width,height,paint);

        // 3.获取图片的dstBitmap
        dstImageViewBitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        dstCanvas = new Canvas(dstImageViewBitmap);
        Drawable drawable = getDrawable();
        drawable.draw(dstCanvas);

        // 4. 获取形状Bitmap
        srcCircleBitmap = Bitmap.createBitmap(width,height,Bitmap.Config.ARGB_8888);
        srcCanvas = new Canvas(srcCircleBitmap);
        paint.setColor(Color.parseColor("#ff0000"));
        paint.setStyle(Paint.Style.FILL);
        srcCanvas.drawOval(0,0,width,height,paint);

        // 5. 设置模式,设置新画布
        int sc = canvas.saveLayer(0,0,width,height,paint,Canvas.ALL_SAVE_FLAG);
        canvas.drawBitmap(dstImageViewBitmap,0,0,paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));
        canvas.drawBitmap(srcCircleBitmap,0,0,paint);
        canvas.restoreToCount(sc);
    }
}

 

上一篇:【spring boot】15.spring boot项目 采用Druid数据库连接池,并启用druid监控功能


下一篇:html5+canvas绘图时使用Smooth.js实现曲线的平滑