开发者

Android ImageView ScaleType *FIT_TOP*

开发者 https://www.devze.com 2023-02-06 12:16 出处:网络
I am trying to implement an ImageView with could holds both landscape or portrait images. Those images should fit the width of the imageview (if landscape) or the height (if portrait) but in any case

I am trying to implement an ImageView with could holds both landscape or portrait images. Those images should fit the width of the imageview (if landscape) or the height (if portrait) but in any case they must be aligned to the top of the view with no margin or padding.

What I would like to achieve is something like android:scaleType="fitStart" but centered in the case of portrait images or aligned to top in case of landscape images.

Added:

Now I am using such an ugly code, which seems to work, but not sure it is the best solution:

<com.custom.layout.MyImageView 
        android:id="@+id/detail_view_image" 
        android:src="@drawable/logo" 
        android:background="#fff"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"
        android:layout_centerHorizontal="true"
        android:cropToPadding="false"
        android:adjustViewBounds="false"
/>

and then in my class, that extends ImageView i do:

@Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int imgWidth = getDrawable().getIntrinsicWidth();
        int imgHeight = getDrawable().getIntrinsicHeight();

        if(imgWidth>imgHeight)
            setScaleType(ScaleType.FIT_START);
        else
            setScaleType(ScaleType.FIT_CENTER);

    开发者_JAVA百科    int width = measureWidth(widthMeasureSpec);
        int height = measureHeight(heightMeasureSpec);      

        setMeasuredDimension(width, height);
    }


Instead of overriding native views you could just place a snippet in onCreate() method that changes the scaleType of the ImageView according to the orientation of the phone.

Some example snippet(I am not sure it works just like that but to get the idea), in onCreate method:

ImageView imgView = findViewById(R.id.myImage);
//portrairt orientation
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
    imgView.setScaleType(ScaleType.FIT_CENTER);
} else { //landscape orientation
    imgView.setScaleType(ScaleType.FIT_START);
}

so when an orientation change is happening then the onCreate will be called again and change the view's scale type and if you are overriding onConfigurationChanged() then you should add the above snippet again wherever you want. Try it and let me know if it worked

0

精彩评论

暂无评论...
验证码 换一张
取 消