Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
388 views
in Technique[技术] by (71.8m points)

android - Resizing ImageView to fit to aspect ratio

I need to resize an ImageView such that it fits to the screen, maintains the same aspect ratio. The following conditions hold:

  • Images are a fixed width (size of the width of screen)
  • Images are downloaded from the Internet, i.e. size can only be determined later
  • Aspect ratio for each image will vary; some are tall, some are square, some are flat
  • ImageView's height needs to change, either bigger or smaller based on the aspect ratio of the
  • Excess height is cropped, can't have a lot of empty space like it is by default.

For example, a tiny 50x50 image on a 400 px width screen would scale the image up to 400x400 px. A 800x200 image would scale to 400x100.

I've looked at most of the other threads, and many proposed solutions like simply changing adjustViewBounds and scaleType will only scale down an image, and not scale it up.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I created it with the help of this Bob Lee's answer in this post: Android: How to stretch an image to the screen width while maintaining aspect ratio?

package com.yourpackage.widgets;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;

public class AspectRatioImageView extends ImageView {

    public AspectRatioImageView(Context context) {
        super(context);
    }

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

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

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width = MeasureSpec.getSize(widthMeasureSpec);
        int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
        setMeasuredDimension(width, height);
    }
}

Now to use it in the XML:

<com.yourpackage.widgets.AspectRatioImageView android:layout_centerHorizontal="true"
    android:src="@drawable/yourdrawable" android:id="@+id/image"
    android:layout_alignParentTop="true" android:layout_height="wrap_content"
    android:layout_width="match_parent" android:adjustViewBounds="true" />

Have fun!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...