2013-02-18 115 views
2

我試圖同時縮放和裁剪圖像,並從左到右的屏幕邊緣顯示它。我收到的圖像比用戶屏幕寬只是點點,我能夠擴展它像這樣(XML):XML中的縮放和裁剪圖像

<ImageView 
     android:id="@+id/category_image_top" 
     android:layout_width="match_parent" 
     android:layout_height="170dp" 
     android:maxHeight="170dp" 
     android:scaleType="centerCrop" 
     android:adjustViewBounds="true" 
     android:focusable="false" 
     /> 

但是,這是我所得到的: What I get

我想像這樣對齊右上角的圖像: What I want

這可能嗎?我已經嘗試過所有scaleType,但注意到了作品,圖像被縮放以適合X和Y(fitXY,fitStart)或圖像裁剪但居中(centerCrop)。我需要像android一樣的東西:scaleType =「cropStart」

+0

可能更容易做到這一點的代碼比XML您設定的圖像之前,那麼你就必須更細粒度的控制 – serenskye 2013-02-18 13:58:42

+0

是的,代碼是我的選擇b。但對我來說這很奇怪,這是無法解決的問題(至少我不能:))。如果您有選擇適合關於明星的圖像,爲什麼不能在開始時裁剪圖像? – paxx 2013-02-18 14:04:17

回答

0

因爲我沒有找到通過xml(視圖)處理這種情況的方法,所以我轉向(如@serenskye建議)來編碼。這裏是我的代碼,我希望它有助於(PS:我改變了我的邏輯一點點,我希望通過寬度因此我將擴展到預定義imageWidght以適應圖像,然後將其裁剪爲imageHeight)

//bm is received image (type = Bitmap) 
Bitmap scaledImage = null; 
float scaleFactor = (float) bm.getWidth()/(float) imageWidth; 

//if scale factor is 1 then there is no need to scale (it will stay the same) 
if (scaleFactor != 1) { 
    //calculate new height (with ration preserved) and scale image 
    int scaleHeight = (int) (bm.getHeight()/scaleFactor);      
    scaledImage = Bitmap.createScaledBitmap(bm, imageWidth, scaleHeight, false); 
} 
else { 
    scaledImage = bm; 
} 

Bitmap cropedImage = null; 
//if cropped height is bigger then image height then there is no need to crop 
if (scaledImage.getHeight() > imageHeight) 
    cropedImage = Bitmap.createBitmap(scaledImage, 0, 0, imageWidth, imageHeight); 
else 
    cropedImage = scaledImage; 

iv.setImageBitmap(cropedImage); 
2
<ImageView 
     android:id="@+id/category_image_top" 
     android:layout_width="match_parent" 
     android:layout_height="170dp" 
     android:maxHeight="170dp" 
     android:scaleType="centerCrop" 
     android:paddingLeft="half of your screen width" 
     android:paddingBottom="half of your screen height" 
     android:adjustViewBounds="true" 
     android:focusable="false" 
/> 

您可以設置填充移動圖像向左或向右,也頂部和底部填充到上下移動

+0

'android:scaleType =「centerCrop」'是我的解決方案,謝謝! – Eido95 2017-07-07 23:54:52