调用:(bt是Bitmap)
head_portrait.setImageBitmap(ToRoundBitmap.toRoundBitmap(bt));
转换圆形的方法:
1 package com.ghp.tools; 2 3 import android.graphics.Bitmap; 4 import android.graphics.Canvas; 5 import android.graphics.Color; 6 import android.graphics.Paint; 7 import android.graphics.PorterDuffXfermode; 8 import android.graphics.Rect; 9 import android.graphics.Bitmap.Config; 10 11 public class ToRoundBitmap { 12 /** 13 * 转成圆形图片 14 * 15 * @param bitmap 16 * @return 17 */ 18 public static Bitmap toRoundBitmap(Bitmap bitmap) { 19 int width = bitmap.getWidth(); 20 int height = bitmap.getHeight(); 21 22 final int color = Color.parseColor("#00FF00"); 23 // defaultWidth = width; 24 // defaultHeight = height; 25 26 float roundPx; 27 float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom; 28 if (width <= height) { // 高大于宽 29 roundPx = width / 2; 30 left = 0; 31 top = 0; 32 right = width; 33 bottom = width; 34 height = width; 35 dst_left = 0; 36 dst_top = 0; 37 dst_right = width; 38 dst_bottom = width; 39 } else { // 宽大于高 40 roundPx = height / 2; 41 float clip = (width - height) / 2; 42 left = clip; 43 right = width - clip; 44 top = 0; 45 bottom = height; 46 width = height; 47 dst_left = 0; 48 dst_top = 0; 49 dst_right = height; 50 dst_bottom = height; 51 } 52 53 Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888); 54 Canvas canvas = new Canvas(output); 55 56 final Paint paint = new Paint(); 57 paint.setAntiAlias(true);// 设置画笔无锯齿 58 59 final Rect src = new Rect((int) left, (int) top, (int) right, 60 (int) bottom); 61 final Rect dst = new Rect((int) dst_left, (int) dst_top, 62 (int) dst_right, (int) dst_bottom); 63 canvas.drawARGB(0, 0, 0, 0); // 填充整个Canvas 64 paint.setColor(color); 65 paint.setDither(true); 66 67 canvas.drawCircle(roundPx, roundPx, roundPx, paint);// 画圆 68 paint.setXfermode(new PorterDuffXfermode( 69 android.graphics.PorterDuff.Mode.SRC_IN)); 70 canvas.drawBitmap(bitmap, src, dst, paint); // 以Mode.SRC_IN模式合并bitmap和已经draw了的Circle 71 72 return output; 73 } 74 }
时间: 2024-11-08 04:16:07