Android之畫一個圓角圖形

最近在看OpenCamera的源碼,表示受益很深,項目地址:https://github.com/almalence/OpenCamera

畫一個圓角的圖,使用PorterDuff.Mode的屬性,話不多說,直接上代碼


/**
     *  方形圓角圖片
     *
     * @param bitmap       圖片
     * @param size         要顯示的大小,如果需要截圖從中心截圖
     * @param borderRadius 圓角弧度 到一定值就爲圓了
     * @param color        圖片邊緣顏色
     * @param borderWidth  圖片邊緣寬度
     * @return
     */
    private Bitmap getRoundedCornerBitmap(Bitmap bitmap, int size, int borderRadius, @ColorInt int color, int borderWidth) {
        final int side = Math.min(bitmap.getWidth(), bitmap.getHeight());

        final Bitmap bitmapCropped = Bitmap.createBitmap(bitmap, (bitmap.getWidth() - side) / 2,
                (bitmap.getHeight() - side) / 2, side, side);

        final Bitmap output = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);

        Canvas canvas = new Canvas(output);

        final Paint paint = new Paint();
        final Rect rectSrc = new Rect(0, 0, bitmapCropped.getWidth(), bitmapCropped.getHeight());
        final Rect rect = new Rect(borderWidth, borderWidth, output.getWidth() - borderWidth, output.getHeight() - borderWidth);
        final RectF rectF = new RectF(rect);
        final RectF rectFBorder = new RectF(0, 0, output.getWidth(), output.getHeight());
        final float roundPx = borderRadius;

        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));//取兩層繪製交集,顯示上層
        // 第一個Rect 代表要繪製的bitmap 區域,第二個 Rect 代表的是要將bitmap 繪製在屏幕的什麼地方
        canvas.drawBitmap(bitmapCropped, rectSrc, rect, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_ATOP));//取下層非交集部分與上層交集部分
        canvas.drawRoundRect(rectFBorder, roundPx, roundPx, paint);

        return output;
    }


發佈了137 篇原創文章 · 獲贊 256 · 訪問量 38萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章