2015-10-19 146 views
3

我正在Xamarin上開發移動應用程序。Scale ImageView適合屏幕寬度/高度,同時保持寬高比

在應用程序中,有一個ImageView顯示的圖像太小而不適合屏幕寬度。

我想縮放圖像以適應屏幕的寬度,同時保持寬高比。

axml

<LinearLayout 
    android:id="@+id/overlayImageContainer" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
    <ImageView 
     android:id="@+id/overlayImageView" 
     android:layout_width="fill_parent" 
     android:layout_height="fill_parent" 
     android:adjustViewBounds="true" 
     android:scaleType="fitCenter"/> 
</LinearLayout> 

結果

兩個ImageViews顯示)一個圖像比所述屏幕的寬度寬,和b)一個圖象比所述寬度窄的屏幕

Two ImageViews displaying a) a picture that is wider than the width of the screen and b) a picture that is narrower than the width of the screen

我試過android:scaleTypeandroid:adjustViewBounds="true"沒有成功的各種組合。

回答

3

事實證明有點困難,而且不可能開箱即用。 Manyhavesimilarproblems

我結束了移植@patrick-boos solution到.NET像這樣:

擴展的ImageView類

using Android.Content; 
using Android.Util; 
using Android.Widget; 

namespace Nsa.BigBrotherUtility.Helpers 
{ 
    /// <summary> 
    /// DynamicImageView is a helper extension that overrides OnMeasure in order to scale the said image 
    /// to fit the entire width/or height of the parent container. 
    /// </summary> 
    public class DynamicImageView : ImageView 
    { 
     public DynamicImageView(Context context, IAttributeSet attributeSet) : base(context, attributeSet) 
     { 

     } 

     protected override void OnMeasure(int widthMeasureSpec, int heightMeasureSpec) 
     { 
      int width = MeasureSpec.GetSize(widthMeasureSpec); 
      int height = width * Drawable.IntrinsicHeight/Drawable.IntrinsicWidth; 
      SetMeasuredDimension(width, height); 
     } 

    } 
} 

axml

<Nsa.BigBrotherUtility.Helpers.DynamicImageView 
    android:id="@+id/overlayImageView" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    android:layout_gravity="center_vertical" 
/> 

結果

的600×600的圖像現在拉伸以填充屏幕的寬度,同時保持縱橫比

technical drawing being stretched to fit width of screen

相關問題