1. 程式人生 > >Android中關於Bitmap的裁剪縮放和建立

Android中關於Bitmap的裁剪縮放和建立

Android 中常常需要對圖片進行縮放裁剪等處理,這裡簡單的介紹一下這兩種處理方式的方法

1.裁剪

/**
     * Returns an immutable bitmap from the specified subset of the source
     * bitmap. The new bitmap may be the same object as source, or a copy may
     * have been made. It is initialized with the same density and color space
     * as the original bitmap.
     *
     * @param source   The bitmap we are subsetting
     * @param x        The x coordinate of the first pixel in source
     * @param y        The y coordinate of the first pixel in source
     * @param width    The number of pixels in each row
     * @param height   The number of rows
     * @return A copy of a subset of the source bitmap or the source bitmap itself.
     * @throws IllegalArgumentException if the x, y, width, height values are
     *         outside of the dimensions of the source bitmap, or width is <= 0,
     *         or height is <= 0
     */
    public static Bitmap createBitmap(@NonNull Bitmap source, int x, int y, int width, int height) {
        return createBitmap(source, x, y, width, height, null, false);
    }

將圖片轉換為Bitmap物件,具體如何轉換可以到BitmapFactory中查詢。將轉換了的bitmap物件傳入方法中,x為從橫軸上開始裁剪的開始位置,y為從縱軸上開始裁剪的開始位置,width為需要裁剪的寬度,height為需要裁剪的高度。然後這個方法返回的就是你裁剪的圖片

2.縮放

public Bitmap resizeImage(Bitmap bitmap, int w, int h) {
        Bitmap BitmapOrg = bitmap;
        int width = BitmapOrg.getWidth();
        int height = BitmapOrg.getHeight();
        int newWidth = w;
        int newHeight = h;

        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // if you want to rotate the Bitmap
        // matrix.postRotate(45);
        Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
                height, matrix, true);
        return resizedBitmap;
    }
縮放通過矩陣Matrix來實現,首先獲取原始Bitmap的寬高,然後通過你傳入的寬高來計算縮放的比率,將比率設定給矩陣,然後通過系統提供的api來實現縮放。