1. 程式人生 > >PorterDuffXfermode遮罩製作圓角矩形

PorterDuffXfermode遮罩製作圓角矩形

效果圖:


程式碼一:  activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <ImageView
        android:id="@+id/imgView"
        android:layout_width="250dp"
        android:layout_height="250dp"
        android:layout_centerInParent="true"
        />
</RelativeLayout>
程式碼二:  MainActivity.java
public class MainActivity extends Activity {
	private ImageView iv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		iv = (ImageView) findViewById(R.id.imgView);
		// 建立並載入圖片(通常是不可修改的)
		Bitmap source = BitmapFactory.decodeResource(getResources(),
				R.drawable.xiaohan);
		// 建立一個和原圖Source一樣大小的Bitmap,並以此新建一個畫布Canvas
		final Bitmap result = Bitmap.createBitmap(source.getWidth(),
				source.getHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(result);
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
		// 首先建立並繪製圓角矩形"遮罩"Mask 1.Mask繪製在畫布Canvas上
		RectF rect = new RectF(0, 0, source.getWidth(), source.getHeight());
		float radius = 90.0f;
		paint.setColor(Color.BLACK);
		canvas.drawRoundRect(rect, radius, radius, paint);
		// 2.設定好PorterDuffXfermode模式SRC_IN
		paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
		// 3.在畫布Canvas上繪製原圖
		canvas.drawBitmap(source, 0, 0, paint);
		paint.setXfermode(null);

		iv.setImageBitmap(result);

	}
}