利用PorterDuffXfermode繪制圖片文字

PorterDuffXfermode是Android中用來對圖層進(jìn)行操作的類,類似于數(shù)學(xué)中的交集、并集,將上層(src)和下層(dst)進(jìn)行特定的方式進(jìn)行混合顯示。

構(gòu)造方法:PorterDuffXfermode(PorterDuff.Mode mode)

下圖顯示對應(yīng)的PorterDuff.Mode所對應(yīng)的效果(詳細(xì)參考英勇青銅5大神的簡書

模式效果

這次實(shí)現(xiàn)的圖片文字是用的SrcIn模式,也就是先畫文字然后畫圖,取其交集區(qū)域顯示上層圖層

完整代碼展示

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);
    //        創(chuàng)建一個新畫布,然后在新畫布上進(jìn)行繪制
        int layerId = canvas.saveLayer(0, 0, getWidth(),getHeight() , null, Canvas.ALL_SAVE_FLAG);
        paint.setTextSize(100);
    //  這里使用STROKE模式通過設(shè)置StrokeWidth增加文字的寬度
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(8);
        float i = paint.measureText("圖片文字");
        canvas.drawText("圖片文字",(getWidth()-i)/2,getHeight()/2,paint);
    //        設(shè)置取交集顯示
        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);
    }
}

效果展示

效果展示
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容