我正在尝试让 ImageView 具有特定的宽度(比如 100dips),但要进行缩放以便高度是保持比例的任何值,所以如果 4:3 则 75 dips,如果 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 并没有改善,它只是让整个图像变小(但保持纵横比)。我怎样才能完成我想做的事情?
最佳答案
将以下类添加到您的项目中并像这样更改您的布局
查看
<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);
}
}
关于android-imageview - Android - 缩放 ImageView 以使其宽度始终为 100 dip,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10153611/