android – 将掩码应用于单个叠加视图而不屏蔽整个活动
作者:互联网
我有一个绿色背景的简单活动,我试图提供一个透明圆形区域的红色覆盖.这是我想要完成的效果:
使用我在互联网上找到的代码,这就是我所看到的:
似乎正在发生的事情是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>
有谁知道如何实现这种效果?
解决方法:
好的.在朋友的帮助下,我明白了.事实证明我需要创建一个空的新画布并将其从一个函数传递到另一个函数,然后在新视图上绘制画布,稍后再添加.这是适合我的代码:
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);
标签:android,android-layout,view,layer,clipping 来源: https://codeday.me/bug/20190629/1330688.html