Android ImageView ScaleType *FIT_TOP*

5
我正在尝试实现一个ImageView,它可以容纳横向或纵向的图片。这些图像应该适合ImageView的宽度(如果是横向)或高度(如果是纵向),但无论如何它们必须与视图的顶部对齐,没有边距或填充。
我想要实现的效果类似于`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);
    }

我想做类似的事情,你最终找到解决方案了吗? - Alan Moore
到目前为止还没运气,我最终使用了我上面发布的那段代码... - 0m4r
1个回答

2

不必覆盖原生视图,您只需在onCreate()方法中放置一个片段,根据手机的方向更改ImageView的scaleType。

以下是一些示例片段(我不确定它是否完全正确,但可以理解),在onCreate方法中:

ImageView imgView = findViewById(R.id.myImage);
//portrairt orientation
if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
    imgView.setScaleType(ScaleType.FIT_CENTER);
} else { //landscape orientation
    imgView.setScaleType(ScaleType.FIT_START);
}

当屏幕方向发生变化时,onCreate() 方法将会再次被调用,改变视图的比例类型。如果您正在覆盖 onConfigurationChanged() 方法,则应该在需要的任何地方再次添加上述代码片段。请尝试并告诉我是否有效。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接