我正在尝试获取 ImageView 中显示的图像的实际大小。实际上我的图像比屏幕大,并且 ImageView 正在调整图像大小以显示它。我正在寻找这种新尺寸。
我尝试在自定义 View 中覆盖 ImageView 的 onDraw 方法,但没有得到正确的高度和宽度...
public class LandImageView extends ImageView
{
public LandImageView( Context context )
{
super( context );
}
public LandImageView(Context context, AttributeSet attrs)
{
super(context, attrs);
}
public LandImageView(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
@Override
protected void onDraw( Canvas canvas )
{
super.onDraw( canvas );
int test = this.getWidth();
int test2 = this.getHeight();
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh)
{
super.onSizeChanged(w, h, oldw, oldh);
}
}
你有什么线索吗?
最佳答案
这里的答案都没有真正回答这个问题:
从 ImageView
显示的任意大小的 Bitmap
,找到 显示图像的实际尺寸,而不是提供的 Bitmap
的尺寸。
即:
- 使用
ImageView.getDrawable().getInstrinsicWidth()
和getIntrinsicHeight()
都会返回原始尺寸。 - 通过
ImageView.getDrawable()
获取Drawable
并将其转换为BitmapDrawable
,然后使用BitmapDrawable.getBitmap() .getWidth()
和getHeight()
还返回原始图像及其尺寸。
获得显示图像的实际尺寸的唯一方法是提取并使用用于显示图像的变换Matrix
。这必须在测量阶段之后完成,这里的示例显示它在 onMeasure()
的 Override
中为自定义 ImageView
调用:
public class SizeAwareImageView extends ImageView {
public SizeAwareImageView(Context context) {
super(context);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
// Get image matrix values and place them in an array
float[] f = new float[9];
getImageMatrix().getValues(f);
// Extract the scale values using the constants (if aspect ratio maintained, scaleX == scaleY)
final float scaleX = f[Matrix.MSCALE_X];
final float scaleY = f[Matrix.MSCALE_Y];
// Get the drawable (could also get the bitmap behind the drawable and getWidth/getHeight)
final Drawable d = getDrawable();
final int origW = d.getIntrinsicWidth();
final int origH = d.getIntrinsicHeight();
// Calculate the actual dimensions
final int actW = Math.round(origW * scaleX);
final int actH = Math.round(origH * scaleY);
Log.e("DBG", "["+origW+","+origH+"] -> ["+actW+","+actH+"] & scales: x="+scaleX+" y="+scaleY);
}
}
注意:要从一般代码中获取图像变换Matrix
(如在Activity
中),函数是ImageView .getImageMatrix()
- 例如myImageView.getImageMatrix()
关于android - 试图在 ImageView 中获取图像的显示大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3855218/