您现在的位置是:首页 > 文章详情

利用PorterDuffXfermode绘制图片文字

日期:2018-05-31点击:360

PorterDuffXfermode是Android中用来对图层进行操作的类,类似于数学中的交集、并集,将上层(src)和下层(dst)进行特定的方式进行混合显示。

构造方法:PorterDuffXfermode(PorterDuff.Mode mode)

下图显示对应的PorterDuff.Mode所对应的效果(详细参考英勇青铜5大神的简书

img_983cb2f263d4126bc305a7ec3c3bdc93.png
模式效果

这次实现的图片文字是用的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); } } 

效果展示

img_068979841db8d2a36066b82fb1c867ef.png
效果展示
原文链接:https://yq.aliyun.com/articles/665585
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章