有的时候我们需要圆形或者矩形的位图,比如QQ头像是圆形的,还有圆角矩形的,这些是怎么做到呢?
这涉及到Xfermode,所以有必要先看一下XFermode的概念,可参考这篇文章
http://blog.csdn.net/t12x3456/article/details/10432935
下面给出获取圆形位图的具体代码
public Bitmap getRoundBitmap(){
Paint paint = new Paint();
int color = paint.getColor();
Bitmap bmp = Bitmap.createBitmap(getWidth(), getHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bmp);
canvas.<span style="color:#ff0000;">drawCircle</span>(getWidth()/2, getHeight()/2, Util.dp2px(mContext, 100), paint);
//paint.setColor(color);
paint.setXfermode(new PorterDuffXfermode(<span style="color:#ff0000;">PorterDuff.Mode.SRC_IN</span>));
canvas.drawBitmap(mBmpPhoto, saveMatrix, paint);
return bmp;
}
需要什么样的图形,只需要把drawCircle换成相应的方法即可
上述代码中的
Util.dp2px(mContext, 100)方法是将dp转换成像素
public static int dp2px(Context context, float dipValue) {
<span style="white-space:pre"> </span>final float scale = context.getResources().getDisplayMetrics().density;
<span style="white-space:pre"> </span>return (int) (dipValue * scale + 0.5f);
<span style="white-space:pre"> </span>}
对应的还有将sp转换成像素的
public static int sp2px(Context context, float spValue) {
<span style="white-space:pre"> </span>final float fontScale = context.getResources().getDisplayMetrics().scaledDensity;
<span style="white-space:pre"> </span>return (int) (spValue * fontScale + 0.5f);
<span style="white-space:pre"> </span>}