Bitmap方法總匯

  • Bitmap縮放
    /**
     * 縮放Bitmap
     *
     * @param src    原bitmap
     * @param width  縮放后的寬度
     * @param height 縮放后的高度
     * @return 縮放后的bitmap
     */
    public static Bitmap scaleBitmap(Bitmap src, int width, int height) {
        int srcW = src.getWidth();
        int srcH = src.getHeight();

        Matrix matrix = new Matrix();
        matrix.setScale(((float) width) / srcW, ((float) height) / srcH);

        return Bitmap.createBitmap(src, 0, 0, srcW, srcH, matrix, false);
    }
  • Bitmap裁剪
    /**
     * 將原bitmap裁剪成正方形
     *
     * @param src 原bitmap
     * @return 正方形的bitmap
     */
    public static Bitmap centerCropSquare(Bitmap src) {
        int w = src.getWidth();
        int h = src.getHeight();
        System.out.println(w + "," + h);

        if (w == h) {
            return src;
        } else if (w > h) {
            return Bitmap.createBitmap(src, (w - h) / 2, 0, h, h);
        } else {
            return Bitmap.createBitmap(src, 0, (h - w) / 2, w, w);
        }
    }
    /**
     * 創建圓形的Bitmap
     *
     * @param src 原Bitmap
     * @return 創建的圓形Bitmap
     */
    public static Bitmap createRoundBitmap(Bitmap src) {
        if (src == null) return null;
        Bitmap bmp = centerCropSquare(src);//首先裁剪成正方形
        int size = bmp.getWidth();

        RectF rectF = new RectF(0, 0, size, size);

        Bitmap bg = Bitmap.createBitmap(size, size, bmp.getConfig());
        bg.setDensity(bmp.getDensity()); // <======= 注意
        Canvas canvas = new Canvas(bg);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        canvas.drawRoundRect(rectF, size / 2, size / 2, paint);
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bmp, 0, 0, paint);

        return bg;
    }
  • Bitmap旋轉
    /**
     * 旋轉Bitmap
     * 注:該方法會導致Bitmap大小變大
     *
     * @param src    原bitmap
     * @param degree 旋轉角度
     * @return 旋轉之后的bitmap
     */
    public static Bitmap rotateBitmap(Bitmap src, int degree) {
        Matrix matrix = new Matrix();
        matrix.postRotate(degree);
        return Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), matrix, false);
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容