1. 程式人生 > >android圓形頭像、圖片

android圓形頭像、圖片

public static Bitmap toRoundImage(Bitmap bitmap) {

    float roundPx = 0;
    int rectStartX=0;
    int rectStartY=0;
    Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
            bitmap.getHeight(), Bitmap.Config.ARGB_8888);

    Rect rect=null;

/**
擷取寬高較小的圖片,就是擷取正中間的正方形
*/
    if (bitmap.getWidth()>bitmap.getHeight()){
        roundPx=bitmap.getHeight()/2
;//半徑 rectStartX=(bitmap.getWidth()-bitmap.getHeight())/2; //矩形x開始位置 rect = new Rect(rectStartX, 0, bitmap.getWidth()-rectStartX, bitmap.getHeight());//取中間部分 }else{ roundPx=bitmap.getWidth()/2;//半徑 rectStartY=(bitmap.getHeight()-bitmap.getWidth())/2; //矩形Y開始位置 rect = new
Rect(0, rectStartY, bitmap.getWidth(), bitmap.getHeight()-rectStartY);//取中間部分 } Canvas canvas = new Canvas(output); int color = 0xff424242; Paint paint = new Paint(); RectF rectF = new RectF(rect); paint.setAntiAlias(true); canvas.drawARGB(0, 0, 0, 0); paint.setColor(color); canvas.drawRoundRect(rectF, roundPx, roundPx, paint); //畫拐角,拐角的半徑為正方形的邊長一半 paint.setXfermode(new
PorterDuffXfermode(PorterDuff.Mode.SRC_IN)); canvas.drawBitmap(bitmap, rect, rect, paint); return output; }
 
 
//下面上圖來解釋,就一目瞭然