PorterDuffXfermode合成圆形图片显示不正确

问题:

在使用PorterDuffXfermode合成圆形图片时,一直显示不正确,要不一片黑色的圆,要不是别的原因,找了网上一大片资料,也关闭了硬件加速也不行

alertImageView是要画的控件,可以是View的子类,比如ImageView。

if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB){
     //View从API Level 11才加入setLayerType方法
     //关闭硬件加速
     alertImageView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}

历尽千难万险,总算正常画出来了

有两种方式可以解决:

方法一:使用两个图层绘画,先画图片,再画圆,需要两个图层。模式使用DST_IN

 public void drawBitmap(){
        ImageView alertImageView = (ImageView)this.findViewById(R.id.alertImage);

        //初始化
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
        Bitmap alertBitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(),bitmap.getConfig());
        Canvas canvas = new Canvas(alertBitmap);
        Paint paint = new Paint();

        //画第一个图层
        canvas.drawBitmap(bitmap,0,0,paint);

        //设置混合模式
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_IN));

        //开启新图层
        Bitmap anotherBitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(),bitmap.getConfig());
        Canvas otherCanvas = new Canvas(anotherBitmap);
        Paint otherpaint = new Paint();
        otherCanvas.drawARGB(0, 0, 0, 0);
        otherCanvas.drawCircle(70,70,40,otherpaint);

        //画第二个图
        canvas.drawBitmap(anotherBitmap,0,0,paint);

        alertImageView.setImageBitmap(alertBitmap);
    }

方法二:使用两个图层绘画,先画圆,再画图片,模式使用SRC_IN

 public void drawBitmap2(){
        ImageView alertImageView = (ImageView)this.findViewById(R.id.alertImage);

        //初始化
        Bitmap bitmap = BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher);
         Bitmap alertBitmap = Bitmap.createBitmap(bitmap.getWidth(),bitmap.getHeight(),bitmap.getConfig());
        Canvas canvas = new Canvas(alertBitmap);
        Paint paint = new Paint();

        //画第一个图层
        canvas.drawCircle(70,70,40,paint);

        //设置混合模式
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));

        //画第二个图
        canvas.drawBitmap(bitmap,0,0,paint);

        alertImageView.setImageBitmap(alertBitmap);
    }

猜你喜欢

转载自blog.csdn.net/zcn596785154/article/details/79180145