【问题标题】:Android imageview not respecting maxWidth?Android imageview不尊重maxWidth?
【发布时间】:2011-04-01 14:44:41
【问题描述】:

所以,我有一个应该显示任意图像的图像视图,即从互联网下载的个人资料图片。我希望 ImageView 缩放其图像以适应父容器的高度,并将最大宽度设置为 60dip。但是,如果图像是高比例的,并且不需要完整的 60dip 宽度,则 ImageView 的宽度应该减小,以便视图的背景紧贴图像周围。

我试过了,

<ImageView android:id="@+id/menu_profile_picture"
    android:layout_width="wrap_content"
    android:maxWidth="60dip"
    android:layout_height="fill_parent"
    android:layout_marginLeft="2dip"
    android:padding="4dip"
    android:scaleType="centerInside"
    android:background="@drawable/menubar_button"
    android:layout_centerVertical="true"/>

但是由于某种原因,这使得 ImageView 变得超级大,也许它使用了图像的固有宽度和 wrap_content 来设置它 - 无论如何,它不尊重我的 maxWidth 属性.. 这只适用于某些类型的容器?它在一个线性布局中......

有什么建议吗?

【问题讨论】:

    标签: android scaling imageview


    【解决方案1】:

    如果您使用match_parent,设置adjustViewBounds 没有帮助,但解决方法是简单的自定义ImageView

    
    public class LimitedWidthImageView extends ImageView {
        public LimitedWidthImageView(Context context) {
            super(context);
        }
    
        public LimitedWidthImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public LimitedWidthImageView(Context context, AttributeSet attrs, int defStyleAttr) {
            super(context, attrs, defStyleAttr);
        }
    
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            int specWidth = MeasureSpec.getSize(widthMeasureSpec);
            int maxWidth = getMaxWidth();
            if (specWidth > maxWidth) {
                widthMeasureSpec = MeasureSpec.makeMeasureSpec(maxWidth,
                        MeasureSpec.getMode(widthMeasureSpec));
            }
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
    

    【讨论】:

    • adjustViewBounds 对我来说似乎适用于 match_parent 宽度。
    【解决方案2】:

    啊,

    android:adjustViewBounds="true"
    

    是 maxWidth 工作所必需的。

    现在工作!

    【讨论】:

    • 谢谢分享,能把你的答案标记为正确吗!?
    • 非常感谢.. 对我来说效果很好:)
    • 并以编程方式:imageView.setAdjustViewBounds(true);
    • 对于遇到此发现不起作用的任何人,请确保未将宽度/高度设置为 match_parent。
    • 在这里,我一直在窃取 AOSP 的特殊内部 ImageView,据说它是为了尊重这些界限而创建的。
    猜你喜欢
    • 2020-03-14
    • 2019-08-01
    • 1970-01-01
    • 2012-06-24
    • 1970-01-01
    • 2011-04-06
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多