1. 程式人生 > >Android Bitmap 常見的幾個操作:縮放,裁剪,旋轉,偏移

Android Bitmap 常見的幾個操作:縮放,裁剪,旋轉,偏移

/**
     * 根據給定的寬和高進行拉伸
     *
     * @param origin    原圖
     * @param newWidth  新圖的寬
     * @param newHeight 新圖的高
     * @return new Bitmap
     */
    private Bitmap scaleBitmap(Bitmap origin, int newWidth, int newHeight) {
        if (origin == null) {
            return null;
        }
        int
height = origin.getHeight(); int width = origin.getWidth(); float scaleWidth = ((float) newWidth) / width; float scaleHeight = ((float) newHeight) / height; Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight);// 使用後乘 Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false
); if (!origin.isRecycled()) { origin.recycle(); } return newBM; } /** * 按比例縮放圖片 * * @param origin 原圖 * @param ratio 比例 * @return 新的bitmap */ private Bitmap scaleBitmap(Bitmap origin, float ratio) { if (origin == null
) { return null; } int width = origin.getWidth(); int height = origin.getHeight(); Matrix matrix = new Matrix(); matrix.preScale(ratio, ratio); Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false); if (newBM.equals(origin)) { return newBM; } origin.recycle(); return newBM; } /** * 裁剪 * * @param bitmap 原圖 * @return 裁剪後的影象 */ private Bitmap cropBitmap(Bitmap bitmap) { int w = bitmap.getWidth(); // 得到圖片的寬,高 int h = bitmap.getHeight(); int cropWidth = w >= h ? h : w;// 裁切後所取的正方形區域邊長 cropWidth /= 2; int cropHeight = (int) (cropWidth / 1.2); return Bitmap.createBitmap(bitmap, w / 3, 0, cropWidth, cropHeight, null, false); } /** * 選擇變換 * * @param origin 原圖 * @param alpha 旋轉角度,可正可負 * @return 旋轉後的圖片 */ private Bitmap rotateBitmap(Bitmap origin, float alpha) { if (origin == null) { return null; } int width = origin.getWidth(); int height = origin.getHeight(); Matrix matrix = new Matrix(); matrix.setRotate(alpha); // 圍繞原地進行旋轉 Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false); if (newBM.equals(origin)) { return newBM; } origin.recycle(); return newBM; } /** * 偏移效果 * @param origin 原圖 * @return 偏移後的bitmap */ private Bitmap skewBitmap(Bitmap origin) { if (origin == null) { return null; } int width = origin.getWidth(); int height = origin.getHeight(); Matrix matrix = new Matrix(); matrix.postSkew(-0.6f, -0.3f); Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false); if (newBM.equals(origin)) { return newBM; } origin.recycle(); return newBM; }