閱讀925 返回首頁    go 阿裏雲 go 技術社區[雲棲]


Android長方形圖片生成正圓形,以及矩形圖片生成圓角

一般要做正圓形圖片,隻能是正方形的基礎上才能實現,否則就變成橢圓了,下麵說說如何使長方形的圖片生成正圓形圖片

廢話不多說,沒圖沒真相,先上圖吧:

原圖:




變成正圓後:




下麵上代碼:

    public static Bitmap makeRoundCorner(Bitmap bitmap)
    {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        int left = 0, top = 0, right = width, bottom = height;
        float roundPx = height/2;
        if (width > height) {
            left = (width - height)/2;
            top = 0;
            right = left + height;
            bottom = height;
        } else if (height > width) {
            left = 0;
            top = (height - width)/2;
            right = width;
            bottom = top + width;
            roundPx = width/2;
        }
        ZLog.i(TAG, "ps:"+ left +", "+ top +", "+ right +", "+ bottom);

        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        int color = 0xff424242;
        Paint paint = new Paint();
        Rect rect = new Rect(left, top, right, bottom);
        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;
    }


下麵再解釋下:

由於圖片是長方形,所以圖片的 寬、高 肯定會有一邊要小於另一邊,要生成正方形就已最小的一邊為基準,再來裁切定位另一邊的顯示範圍

至於圓角的半徑則是正方形寬的一半,用過 CSS 的就知道,畫圓很方便 border-radius設為 50% 就可以了,都是一個道理

android 的 UI 真是太繁瑣了


矩形畫個圓角的代碼:

    public static Bitmap makeRoundCorner(Bitmap bitmap, int px)
    {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        int color = 0xff424242;
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, width, height);
        RectF rectF = new RectF(rect);
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, px, px, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
        return output;
    }







最後更新:2017-04-03 12:55:41

  上一篇:go 算法訓練-黑白格子
  下一篇:go C#如何判斷操作係統位數是32位還是64位