I have a simple activity with a green background, and I try to provide a red overlay with a transparent round area. Here is the effect I'm trying to accomplish:
Expected Image
With the code I found on the Internet, this is what I see:
Code result
It seems that PorterDuff applies itself to all representations in action, and not to what I clearly tell him. Many of the messages on Stack concerned masking a bitmap with a different bitmap, and I'm trying to mask part of a view with a programmatically created circular shape. Here is the code I'm trying to use:
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 ); } }
with layout xml file as such
<?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>
Does anyone know how to achieve the effect?
source share