在ImageView to Height中缩放图像,保持宽高比在屏幕边界之外,并对齐

时间:2017-02-02 16:08:29

标签: java android xml android-layout

我想要一个图像,我希望与屏幕的高度相匹配,延伸超过屏幕的左边缘,将图像的右侧与屏幕的右侧对齐。

最好使用XML解决方案,但Java解决方案也可以。

我该怎么做? Example Scaling

1 个答案:

答案 0 :(得分:2)

您需要使用矩阵缩放并自行设置矩阵。这并不难。

在布局视图后,您必须执行此操作,以便获得ImageView的尺寸。您还需要设置DrawableBitmap的尺寸。

  • 首先,您要弄清楚您需要多少缩放(乘)图像,以使高度与ImageView的高度相同。为此,您只需将ImageView高度除以图像高度。

  • 现在您也知道图像的宽度。要获得图像的右边缘并使ImageView对齐,您需要将图像向左移动(平移),然后将其移回ImageView的宽度。因此,平移只是图像宽度与ImageView宽度的差异。

我是这样做的:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final ImageView imageView = (ImageView) findViewById(R.id.imageview);

        imageView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                BitmapDrawable drawable = null;
                if (Build.VERSION.SDK_INT >= 21) {
                    drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.sunset, getTheme());
                } else {
                    drawable = (BitmapDrawable) getResources().getDrawable(R.drawable.sunset);
                }
                Bitmap bitmap = drawable.getBitmap();

                // get the scale factor that will have to be applied to
                // the image to make it the same height as your ImageView
                float factor = (float) imageView.getHeight() / (float) bitmap.getHeight();

                // now the image will have to be shifted over all of its
                // width minus the width of the ImageView.  This will make
                // the right edges line up.
                int scaledImageWidth = (int) (bitmap.getWidth() * factor);
                int translateX = imageView.getWidth() - scaledImageWidth;

                // you can also use drawable.getIntrinsicWidth() and
                //     drawable.getIntrinsicHeight()

                Matrix matrix = new Matrix();
                matrix.setScale(factor, factor);
                matrix.postTranslate(translateX, 0);

                imageView.setScaleType(ImageView.ScaleType.MATRIX);
                imageView.setImageMatrix(matrix);
                imageView.setImageBitmap(bitmap);
            }
        });
    }