PorterDuffXfermode是Android中用来对图层进行操作的类,类似于数学中的交集、并集,将上层(src)和下层(dst)进行特定的方式进行混合显示。
构造方法:PorterDuffXfermode(PorterDuff.Mode mode)
下图显示对应的PorterDuff.Mode所对应的效果(详细参考英勇青铜5大神的简书)
这次实现的图片文字是用的SrcIn模式,也就是先画文字然后画图,取其交集区域显示上层图层
完整代码展示
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);
}
}