【问题标题】:How proportionally scale any image (of imageview) with width equal to "match_parent"?如何按比例缩放宽度等于“match_parent”的任何图像(图像视图)?
【发布时间】:2013-10-16 08:45:03
【问题描述】:

我可能有不同的drawable(大或小),我总是跨越宽度(match_parent)并按比例增加或减少高度。保持比例。

这怎么可能?

我试过了:

<ImageView
            android:id="@+id/iv_TEST"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
android:adjustViewBounds="true"
            android:scaleType="fitXY"
            android:src="@drawable/test" />

问题是它增加或减少宽度,看起来很糟糕。

【问题讨论】:

  • 使用android:scaleType="fitStart" 看看结果是不是你想要的。
  • 你必须得到你的ImageView的父视图的width。因此你可以确定缩放因子。之后你可以得到缩放的drawable并设置它。
  • 不行,图片没有拉伸到填满整个宽度

标签: android android-layout android-imageview android-image android-drawable


【解决方案1】:

已修复。要纠正此问题,您需要执行以下操作:

  1. 自定义图像视图
  2. 将drawable设置为"android:src",来自代码(imageview.setImageResource())

用 ResizableImageView 替换 ImageView:

<"the name of your package".ResizableImageView
            android:id="@+id/iv_test"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            />

ResizableImageView.class

    public class ResizableImageView extends ImageView {
        public ResizableImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public ResizableImageView(Context context) {
            super(context);
        }

        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            Drawable d = getDrawable();
            if (d == null) {
                super.setMeasuredDimension(widthMeasureSpec, heightMeasureSpec);
                return;
            }

            int imageHeight = d.getIntrinsicHeight();
            int imageWidth = d.getIntrinsicWidth();

            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);

            float imageRatio = 0.0F;
            if (imageHeight > 0) {
                imageRatio = imageWidth / imageHeight;
            }
            float sizeRatio = 0.0F;
            if (heightSize > 0) {
                sizeRatio = widthSize / heightSize;
            }

            int width;
            int height;
            if (imageRatio >= sizeRatio) {
                // set width to maximum allowed
                width = widthSize;
                // scale height
                height = width * imageHeight / imageWidth;
            } else {
                // set height to maximum allowed
                height = heightSize;
                // scale width
                width = height * imageWidth / imageHeight;
            }

            setMeasuredDimension(width, height);
        }
    }

解决方案:I need to size the imageView inside my table row programatically

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2017-10-15
    • 1970-01-01
    • 2018-11-18
    • 1970-01-01
    相关资源
    最近更新 更多