2015-04-03 84 views
1

我想創建一個應用程序,查看圖像/海報,我想在正方形imageView。在此之前,我試圖讓屏幕寬度,並將其分配給圖像的高度和寬度,這樣的事情如何在android中設置imageView以平方視圖?

Bitmap newicon = Bitmap.CreateBitmap (int x, int y, int width, int height, matrix, false/true); 

但有錯誤發生「X +寬< = bitmap.width()」。這是我迄今創建的示例,但我將高度設置爲400dp。我希望高度和寬度靈活取決於手機的大小。有任何想法嗎?

<ImageView 
       android:src="@android:drawable/ic_menu_gallery" 
       android:layout_width="match_parent" 
       android:layout_height="400dp" 
       android:adjustViewBounds="true" 
       android:layout_marginLeft="10dp" 
       android:layout_marginRight="10dp" 
       android:layout_marginTop="10dp" 
       android:scaleType="centerCrop" 
       android:id="@+id/ivPoster" /> 

enter image description here

+0

我想你應該只使用XML來處理這個問題,因爲如果你在你的listview中有很多圖片,並且你爲它們中的每一個都創建了一個新的位圖,你就有可能導致應用程序崩潰的內存異常......我認爲你現在的XML是可以的,但是如果你修正了高度而不是寬度,你將無法得到每個設備的方形圖像。例如,獲取每個設備的方形圖像的一種方法是以編程方式獲取屏幕的寬度,然後設置ImageView的寬度和高度。 – 2015-04-03 03:35:42

+0

你試過'android:scaleType =「fitXY」'。你想適應sqare,那麼你需要從imageview中刪除邊距,我猜。 – Bharatesh 2015-04-03 04:22:24

+0

android:scaleType =「fitXY」 – 2015-04-03 04:46:34

回答

2

您需要使用自定義的ImageView對於這一點,看看這個:

public class SquareImageView extends ImageView { 
    public SquareImageView(Context context) { 
     super(context); 
    } 

    public SquareImageView(Context context, AttributeSet attrs) { 
     super(context, attrs); 
    } 

    public SquareImageView(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
    } 

    protected void onDraw(Canvas canvas) { 
     super.onDraw(canvas); 
    } 

    @Override 
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { 
     super.onMeasure(widthMeasureSpec, heightMeasureSpec); 
     setMeasuredDimension(getMeasuredWidth(), getMeasuredWidth()); // Snap to width 
    } 
} 

在佈局文件,用它來代替的ImageView的。

希望這有助於!

+0

你也可以在這裏使用android:scaleType選項。 – Harry 2015-04-03 06:10:16

+0

哦,謝謝你!一旦我創建了這個課程,我該如何使用它?我怎樣才能把保存圖像的變量發送給這個類。或者它自動得到它?有點模糊對不起 – user3057414 2015-04-03 07:31:06

+0

只需用和高度wrap_content替換。 – Harry 2015-04-03 07:33:19

相關問題