構造方法:PorterDuffXfermode(PorterDuff.Mode mode)android
下圖顯示對應的PorterDuff.Mode所對應的效果canvas
package com.yuyigufen.customview; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.PorterDuff; import android.graphics.PorterDuffXfermode; import android.support.annotation.Nullable; import android.util.AttributeSet; import android.view.View; /** * Created by Administrator on 2018/6/1 0001. */ public class MyTextImageView extends View { private Paint paint; public MyTextImageView(Context context) { this(context,null); } public MyTextImageView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); paint = new Paint(Paint.ANTI_ALIAS_FLAG); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { setMeasuredDimension(measureWidth(widthMeasureSpec),measureWidth(heightMeasureSpec)); } private int measureWidth(int width){ int size = MeasureSpec.getSize(width); int mode = MeasureSpec.getMode(width); if(MeasureSpec.EXACTLY==mode){ return size; }else { if(MeasureSpec.AT_MOST==mode){ return size<200?size:200; } return 200; } } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); // 建立一個新畫布,而後在新畫布上進行繪製 int layerId = canvas.saveLayer(0, 0, getWidth(),getHeight() , null, Canvas.ALL_SAVE_FLAG); paint.setTextSize(100); // 這裏使用STROKE模式經過設置StrokeWidth增長文字的寬度 paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(8); float i = paint.measureText("圖片文字"); canvas.drawText("圖片文字",(getWidth()-i)/2,getHeight()/2,paint); // 設置取交集顯示 PorterDuffXfermode porterDuffXfermode = new PorterDuffXfermode(PorterDuff.Mode.SRC_IN); paint.setXfermode(porterDuffXfermode); Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.fff); // 將圖片縮放爲控件大小 Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, getWidth(), getHeight(), true); canvas.drawBitmap(scaledBitmap,5,5,paint); paint.setXfermode(null); // 將繪製完的畫布貼到控件上 canvas.restoreToCount(layerId); } }