【问题标题】:Get the Height and the Width of drawn area of an ImageView获取 ImageView 绘制区域的高度和宽度
【发布时间】:2013-11-21 11:17:49
【问题描述】:

如果我有一个(800*800 像素)的 ImageView。当我尝试在此 ImageView 之外绘制一条线时,它会绘制

    myBitmap = Bitmap.createBitmap(800,800,Bitmap.Config.ARGB_8888);
    myCanvas = new Canvas(myBitmap);
    myPaint = new Paint();
    myImageView.setImageBitmap(myBitmap);
    myCanvas.drawLine(-100, -100, 600, 600, myPaint);

即使起点在外面,也会画出我的线,

现在我想获得它们的总大小,我的意思是 [900 , 900]。我不知道我可以从哪个组件获得它(myCanvasmyBitmapmyImageView)。

我希望我的问题很清楚。

谢谢。

【问题讨论】:

  • 不,我看到了这个,当使用myImageView.getDrawable().getIntrinsicWidth()myImageView.getDrawable().getIntrinsicHeight()时,它给了我800 X 800
  • myCanvas.getWidth()myCanvas.getHeight() 提供什么?

标签: android imageview size android-canvas


【解决方案1】:

我认为你需要的是:

使用ImageView.getDrawable().getInstrinsicWidth()getIntrinsicHeight() 都将返回原始尺寸。

获得显示图像的实际尺寸的唯一方法是提取和使用用于显示图像的变换矩阵。这必须在测量阶段之后完成,此处的示例显示它在 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);
    }
} 

注意:要从一般代码中获取图像转换矩阵(如在 Activity 中),函数是 ImageView.getImageMatrix() - 例如myImageView.getImageMatrix()

【讨论】:

  • 这也给我800X800
  • @RiadSaadi 你想知道形成的图像的尺寸,包括轮廓吗?
  • 是的,我想要所有绘制区域的大小。例如,如果我画另一条线 (10,10) 到 (1000,1000) 我将从 (-100,-100) 到 (1000,1000) 得到宽度 = 1100 和高度 = 1100
  • 我很抱歉,但即使这样它也给出了原始尺寸 800X800,
【解决方案2】:

我认为在你的bitmap之外绘制的东西丢失了,你可以通过旋转你的ImageView来检查这个,你会看到你bitmap之外的东西是黑色甚至如果你画了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-01
    • 2022-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多