【问题标题】:Android - Scaling ImageView so that it's always 100 dip in widthAndroid - 缩放 ImageView 使其宽度始终为 100
【发布时间】:2012-04-14 12:28:01
【问题描述】:
我试图让 ImageView 具有特定的宽度(比如说 100dips),但要进行缩放,以便高度是保持比例的任何值,所以如果 4:3 则下降 75,如果 4:5 则下降 120下降等。
我尝试了一些方法,但没有任何效果。这是我目前的尝试:
<ImageView
android:id="@+id/image"
android:layout_height="wrap_content"
android:layout_width="100dip"
android:adjustViewBounds="true"
android:src="@drawable/stub"
android:scaleType="fitCenter" />
高度的 wrap_content 并没有改善,它只是使整个图像变小(但确实保持了纵横比)。我怎样才能完成我想做的事?
【问题讨论】:
标签:
android
android-imageview
android-ui
【解决方案1】:
将以下类添加到您的项目中并像这样更改您的布局
查看
<my.package.name.AspectRatioImageView
android:layout_centerHorizontal="true"
android:src="@drawable/my_image"
android:id="@+id/my_image"
android:layout_height="wrap_content"
android:layout_width="100dp"
android:adjustViewBounds="true" />
类
package my.package.name;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.ImageView;
/**
* ImageView which scales an image while maintaining
* the original image aspect ratio
*
*/
public class AspectRatioImageView extends ImageView {
/**
* Constructor
*
* @param Context context
*/
public AspectRatioImageView(Context context) {
super(context);
}
/**
* Constructor
*
* @param Context context
* @param AttributeSet attrs
*/
public AspectRatioImageView(Context context, AttributeSet attrs) {
super(context, attrs);
}
/**
* Constructor
*
* @param Context context
* @param AttributeSet attrs
* @param int defStyle
*/
public AspectRatioImageView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
/**
* Called from the view renderer.
* Scales the image according to its aspect ratio.
*/
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int height = width * getDrawable().getIntrinsicHeight() / getDrawable().getIntrinsicWidth();
setMeasuredDimension(width, height);
}
}