PorterDuffXfermode的简单使用之画圆形头像

时间:2021-09-04 23:13:21

PorterDuffXfermode的用法之教你画圆形头像

  1. 这里我们就直接在onDraw方法中操作了,首先应该创建一个画笔,需要注意的是,创建的画笔不要设置style为stroke,使用默认的即可.
  2. 根据源图实例化一个Bitmap对象,bitmap = BitmapFactory.decodeResource(getResources(),R.drawable.timg);然后再利用该实例创建一个副本(因为Android系统中,是不允许直接修改源图的):bmp = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),Bitmap.Config.ARGB_8888);
  3. 根据Bitmap副本创建一个Canvas对象Canvas mCanvas = new Canvas(bmp);表示之后的绘画操作都是发生在这个副本上的.
  4. 然后利用创建出来的mCanvas对象来画一个圆形遮罩mCanvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,bitmap.getWidth() / 2, paint2);
  5. 接下来就是关键步骤了paint2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));这里就用到了PorterDuffXfermode类了,它就是用来设置draw方法之前和之后图像的关系的:PorterDuffXfermode的简单使用之画圆形头像
  6. 然后将源图画在mCanvas对象上mCanvas.drawBitmap(bitmap, 0, 0, paint2);
  7. 此时副本上的图像就画好了,最后将这个Bitmap画到onDraw方法中指定canvas对象上canvas.drawBitmap(bmp, 0, 0, paint1);

完整代码:

package com.qianyue.testdensity;

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.Paint.Style;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.RectF;
import android.util.AttributeSet;
import android.view.View;

public class DrawPaint extends View {

private static final float WIDTH = 5;
Paint paint1;
Paint paint2;
private Bitmap bitmap;
private Bitmap bmp;

public DrawPaint(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}

public DrawPaint(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}

public DrawPaint(Context context) {
this(context, null);
}

private void init() {
paint1 = new Paint();
paint1.setColor(Color.RED);
paint1.setStrokeWidth(WIDTH);

paint2 = new Paint();
paint2.setAntiAlias(true);
paint2.setStrokeWidth(WIDTH);

setBackgroundColor(Color.TRANSPARENT);

bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.timg);
bmp = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(),
Bitmap.Config.ARGB_8888);
}

@Override
protected void onDraw(Canvas canvas) {

Canvas mCanvas = new Canvas(bmp);

mCanvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
bitmap.getWidth() / 2, paint2);
paint2.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
mCanvas.drawBitmap(bitmap, 0, 0, paint2);

canvas.drawBitmap(bmp, 0, 0, paint1);
}

@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int getWidth = bitmap.getWidth();
int getHeight = bitmap.getHeight();

int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);

int newWidth = MeasureSpec.makeMeasureSpec(getWidth, widthMode);
int newHeight = MeasureSpec.makeMeasureSpec(getHeight, heightMode);

super.onMeasure(newWidth, newHeight);
}

}

效果图

v怪客 PorterDuffXfermode的简单使用之画圆形头像