Android 圓形圖片加白邊加陰影

/**
     * 將圖片準轉爲圓形
     * 
     * @param bitmap
     * @return
     */
    public static Bitmap getRoundedCornerBitmap(String path, Bitmap bitmap) {

        int size = bitmap.getWidth() < bitmap.getHeight() ? bitmap.getWidth()
                : bitmap.getHeight();
        Bitmap output = Bitmap.createBitmap(size, size, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, size, size);
        final float roundPx = size / 2;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawCircle(roundPx, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);

        ImageCruCache.getInstance().addBitmapToMemoryCache(path, output);
        return getRoundeBitmapWithWhite(path, output);
    }

    /**
     * 獲取白色邊框
     * 
     * @param path
     * @param bitmap
     * @return
     */
    public static Bitmap getRoundeBitmapWithWhite(String path, Bitmap bitmap) {
        int size = bitmap.getWidth() < bitmap.getHeight() ? bitmap.getWidth()
                : bitmap.getHeight();
        int num = 14;
        int sizebig = size + num;
        Bitmap output = Bitmap.createBitmap(sizebig, sizebig, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = Color.parseColor("#FFFFFF");
        final Paint paint = new Paint();
        final float roundPx = sizebig / 2;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawBitmap(bitmap, num / 2, num / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(Mode.DST_ATOP));

        RadialGradient gradient = new RadialGradient(roundPx, roundPx, roundPx,
                new int[] { Color.WHITE, Color.WHITE,
                        Color.parseColor("#AAAAAAAA") }, new float[] { 0.f,
                        0.97f, 1.0f }, Shader.TileMode.CLAMP);
        paint.setShader(gradient);
        canvas.drawCircle(roundPx, roundPx, roundPx, paint);

        ImageCruCache.getInstance().addBitmapToMemoryCache(path, output);
        return output;
    }

分兩步執行,第一步:getRoundedCornerBitmap方法執行將圖片轉換爲正圓;canvas

第二部:getRoundeBitmapWithWhite設置白色邊框而且添加陰影spa

若是不喜歡陰影,能夠考慮去掉paint的陰影效果code

 

這裏有一個很是重要的事情:createBitmap必定要使用 Config.ARGB_8888  否則就沒有效果。具體緣由有待研究。blog

相關文章
相關標籤/搜索