4

我有一个绿色背景的简单活动,我试图提供一个带有透明圆形区域的红色叠加层。这是我想要实现的效果:

预期图像

使用我在互联网上找到的代码,这就是我所看到的:

代码结果

似乎正在发生的事情是 PorterDuff 将自己应用于活动中的所有视图,而不是我明确告诉它的视图。Stack 上的许多帖子都是关于用另一个位图掩盖一个位图,而我正试图用一个以编程方式创建的圆形来掩盖视图的一部分。这是我尝试使用的代码:

public class ClippingTestActivity extends Activity {
    private Paint mPaint;
    ClippingView ddd;
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.test);
        View v = new View(this.getBaseContext());
        v.setBackgroundColor(Color.GREEN);
        this.addContentView(v, new  LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));

         ClippingView r = new ClippingView(this.getBaseContext());
        r.setBackgroundColor(Color.RED);   
        this.addContentView(r, new   LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
    }

}

    public class ClippingView extends View {
    Paint paint = new Paint();
        Path path = new Path();
        public ClippingView(Context context) {
    super(context);
    }
    @Override
    public void onDraw(Canvas canvas) {
    super.onDraw( canvas );

        paint.setColor(Color.TRANSPARENT);
        paint.setStyle(Style.FILL);

        paint.setXfermode( new PorterDuffXfermode( Mode.CLEAR ) );
        int cx = 200;
        int cy = 200;
        int radius = 50;
        canvas.drawCircle( cx, cy, radius, paint );
    }
}

布局xml文件就是这样

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res/com.appspot.scruffapp" 
 android:layout_width="fill_parent" 
 android:layout_height="fill_parent"         
 android:layout_centerHorizontal="true"
 android:background="#ff0000"> 
 </RelativeLayout> 

有谁知道如何实现效果?

4

1 回答 1

3

好的。在朋友的帮助下,我想通了。事实证明,我需要创建一个空的新画布,并将其从一个函数传递到另一个函数,然后在一个稍后添加的新视图上绘制画布。这是对我有用的代码:

Bitmap circle = DrawView.makeCircle(drawable);
Bitmap overlayBg = DrawView.makeOverlayBg(canvas.getWidth(),canvas.getHeight());

Bitmap finalImage = Bitmap.createBitmap(canvas.getWidth(),canvas.getHeight(), Bitmap.Config.ARGB_8888);

final android.graphics.Canvas tmpCanvas = new android.graphics.Canvas(finalImage);
tmpCanvas.drawBitmap(overlayBg, 0, 0, null);

final android.graphics.Paint paint = new android.graphics.Paint();
paint.setXfermode(new android.graphics.PorterDuffXfermode(Mode.DST_OUT));
tmpCanvas.drawBitmap(circle, cx - radius, cy - radius, paint);

canvas.drawBitmap(finalImage, 0, 0, null); 
于 2012-12-28T17:41:11.727 回答