我正在尝试实现一个ImageView,它可以容纳横向或纵向的图片。这些图像应该适合ImageView的宽度(如果是横向)或高度(如果是纵向),但无论如何它们必须与视图的顶部对齐,没有边距或填充。
我想要实现的效果类似于`android:scaleType="fitStart"`,但在纵向图像的情况下居中,在横向图像的情况下与顶部对齐。
补充:
现在我正在使用如此丑陋的代码,它似乎能工作,但不确定是否是最佳解决方案:
我想要实现的效果类似于`android:scaleType="fitStart"`,但在纵向图像的情况下居中,在横向图像的情况下与顶部对齐。
补充:
现在我正在使用如此丑陋的代码,它似乎能工作,但不确定是否是最佳解决方案:
<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"
/>
然后,在我继承ImageView的类中,我执行以下操作:
@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);
int width = measureWidth(widthMeasureSpec);
int height = measureHeight(heightMeasureSpec);
setMeasuredDimension(width, height);
}