繁体   English   中英

Android ImageView缩放图像并居中

[英]Android ImageView scale image and center

我需要在ImageView内缩放Image,我需要使用矩阵,

这样我

private void scaleImage(float scaleFactor, float focusX,float focusY) {
    Matrix displayMatrix= new Matrix();
    matrix.postScale(scaleFactor, scaleFactor);
    displayMatrix.set(matrix);
    imageView.setImageMatrix(displayMatrix);
}

问题是无论我无法在ImageView中居中放置图像,

我需要将图像放在中心(如果图像小于视图,则留白边)

我已经摇头几个小时了,请帮忙。


我已经广泛浏览了这个https://stackoverflow.com/a/6172226/1815311,但没有成功。

您要做的就是找到新的x和y坐标将图像放置在何处,然后平移矩阵,以便图像移动到ImageView的中心。 您的整个scaleImage方法可以如下所示:

private void scaleImage(float scaleFactor, float focusX, float focusY) {
    Matrix displayMatrix = new Matrix();
    Matrix matrix = imageView.getImageMatrix();

    float x = (imageView.getWidth() - imageView.getDrawable().getIntrinsicWidth() * scaleFactor) / 2;
    float y = (imageView.getHeight() - imageView.getDrawable().getIntrinsicHeight() * scaleFactor) / 2;

    matrix.postScale(scaleFactor, scaleFactor);
    matrix.postTranslate(x, y);

    displayMatrix.set(matrix);
    imageView.setImageMatrix(displayMatrix);
}

试试我的代码,希望对您有所帮助:

 private void scaleImage(ImageView view, int boundBoxInDp)
{ 
 // Get the ImageView and its bitmap
 Drawable drawing = view.getDrawable();
 Bitmap bitmap = ((BitmapDrawable)drawing).getBitmap();

 // Get current dimensions
 int width = bitmap.getWidth();
 int height = bitmap.getHeight();

 // Determine how much to scale: the dimension requiring less scaling is
 // closer to the its side. This way the image always stays inside your
 // bounding box AND either x/y axis touches it.
 float xScale = ((float) boundBoxInDp) / width;
 float yScale = ((float) boundBoxInDp) / height;
 float scale = (xScale <= yScale) ? xScale : yScale;

// Create a matrix for the scaling and add the scaling data
 Matrix matrix = new Matrix();
 matrix.postScale(scale, scale);

  // Create a new bitmap and convert it to a format understood by the ImageView
  Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, width, height, matrix, true);
  BitmapDrawable result = new BitmapDrawable(scaledBitmap);
  width = scaledBitmap.getWidth();
  height = scaledBitmap.getHeight();

 // Apply the scaled bitmap
 view.setImageDrawable(result);

 // Now change ImageView's dimensions to match the scaled image
 LinearLayout.LayoutParams params (LinearLayout.LayoutParams)view.getLayoutParams();
 params.width = width;
 params.height = height;
 view.setLayoutParams(params);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM