2014-10-08 160 views
12

如何從左側和右側剪切矩形圖像(600 x 300)以適應方形ImageView?我不想調整圖片大小,我只是想裁剪,是300×300將圖像裁剪爲正方形 - Android

[解決方法]

正如@blackbelt說

Bitmap cropImg = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);

是偉大的裁剪圖像。那麼如何自動裁剪不同尺寸的圖像。我創建這個簡單的代碼爲:

// From drawable 
Bitmap src= BitmapFactory.decodeResource(context.getResources(), R.drawable.image); 

// From URL 
Bitmap src = null; 
try { 
    String URL = "http://www.example.com/image.jpg"; 
    InputStream in = new java.net.URL(URL).openStream(); 
    src = BitmapFactory.decodeStream(in); 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

int width = src.getWidth(); 
int height = src.getHeight(); 
int crop = (width - height)/2; 
Bitmap cropImg = Bitmap.createBitmap(src, crop, 0, height, height); 

ImageView.setImageBitmap(cropImg); 

回答

3

您可以使用

Bitmap dst = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight); 

從文檔:

返回從源 位圖的指定子集的不可變位。新的位圖可能與源相同,或者可能有複製品 。它使用與原始位圖相同的密度進行初始化。

Here你可以找到的文檔

16

擴大一點上回答上述

由於在某些情況下,你可以用例外最終沒有預期結果,只是通過使用Bitmap.createBitmap(),就像下面這樣:

java.lang.IllegalArgumentException異常:X +寬度必須< = bitmap.width()

赫雷什是一個小的函數,它的作物和處理的某些情況下,公共。

編輯:根據droidster的說法更新。

public static Bitmap cropToSquare(Bitmap bitmap){ 
    int width = bitmap.getWidth(); 
    int height = bitmap.getHeight(); 
    int newWidth = (height > width) ? width : height; 
    int newHeight = (height > width)? height - (height - width) : height; 
    int cropW = (width - height)/2; 
    cropW = (cropW < 0)? 0: cropW; 
    int cropH = (height - width)/2; 
    cropH = (cropH < 0)? 0: cropH; 
    Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight); 

    return cropImg; 
} 

我做了幾個不同分辨率和大小的圖像測試,它按預期工作。

它也可以在其他情況下使用,例如當您試圖製作一個「完美」圓形圖像並需要傳遞方形位圖等時

+1

這正是我一直在尋找,獲得完美的圓形圖像,而不是橢圓形。但是,如果圖像的高度大於寬度,則不會在中心裁剪,因爲在createBitmap方法中y參數的值爲0。這是如何解決的:添加這兩行:'int cropH =(height - width)/ 2; \t cropH =(cropH <0)? 0:cropH;'使用cropH作爲y值。 \t'位圖cropImg = Bitmap.createBitmap(位圖,cropW,cropH,newWidth,newHeight);' – 2015-03-14 14:12:52

+0

不錯,我看到你的觀點....基本上要對寬度和高度進行相同的計算。 – 2015-04-18 20:49:22

1

組固定圖像視圖的高度,寬度,並設置兩個屬性,以圖像視圖

android:adjustViewBounds="true" 
android:scaleType="centerCrop"