这是一个小的添加,用来标记 martinsson 。
如果图像的宽度大于它的高度,那么标记的解决方案将在屏幕的顶部和底部留下空间。
below 通过首先比较宽度和高度来修复这里问题: 如果图像宽度> = 高度,则它将缩放高度以匹配屏幕高度,然后缩放宽度以保留纵横比。 同样,如果图像高度> 宽度,那么它将缩放宽度以匹配屏幕宽度,然后缩放高度以保持长宽比。
换句话说,它正确地满足了 scaleType="centerCrop"的定义:
均匀缩放图像,使图像的大小为( 宽度和高度) 磅图像的大小等于或者等于视图的相应尺寸的磅。package com.mypackage;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.widget.ImageView;
public class FixedCenterCrop extends ImageView
{
public FixedCenterCrop(final Context context, final AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onMeasure(final int widthMeasureSpec, final int heightMeasureSpec)
{
final Drawable d = this.getDrawable();
if(d!= null) {
int height = MeasureSpec.getSize(heightMeasureSpec);
int width = MeasureSpec.getSize(widthMeasureSpec);
if(width> = height)
height = (int) Math.ceil(width * (float) d.getIntrinsicHeight()/d.getIntrinsicWidth());
else
width = (int) Math.ceil(height * (float) d.getIntrinsicWidth()/d.getIntrinsicHeight());
this.setMeasuredDimension(width, height);
} else {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
}
这里解决方案在 portrait 或者 横向模式 中自动运行。 你在布局中引用它,就像在标记中做的那样。 比如:
android:id="@+id/imgLoginBackground"
android:src="@drawable/mybackground"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:scaleType="centerCrop"/>