如何找到的ImageView的宽度/高度? [英] How do I find the width/height of ImageView?
问题描述
我的问题是类似这个问题。我用此code 延长的ImageView形成TouchImageView。在我的onCreate()方法,我想打电话给
My question is similar to this question. I've used this code to extend ImageView to form TouchImageView. In my onCreate() method, I want to call
setImage(Bitmap bm, int displayWidth, int displayHeight)
但我不知道宽度或高度使用。当我打电话的getHeight(),它给了我零。
but I don't know the width or height to use. When I call getHeight(), it gives me zero.
我尝试使用 kcoppock 的答案的 pviously提到的$ P $的问题,但没有成功。上preDraw()监听器被调用每秒几次,我无法弄清楚如何一次调用它。
I tried to avoid the 0 using kcoppock's answer to the previously mentioned question, but was unsuccessful. The onPreDraw() listener is called several times per second and I can't figure out how to only call it once.
推荐答案
这是一个脆弱的做法这样的事情。 Android的意见是由其父查看使用 onMeasure
法测定。通过提供一个初始大小设置为 setImage
的方法扩展到(特别是如果你将其设置根据显示器尺寸)您邀请的复杂性时,你要嵌套这个视图在其他人。像平板电脑较大的屏幕设备是一个很好的例子。
That's a brittle approach for something like this. Android Views are measured by their parent View using the onMeasure
method. By providing an initial size to a setImage
method to scale to (and especially if you set it based on the display size) you're inviting complexity whenever you want to nest this View within others. Larger screen devices like tablets are a good example of this.
一个更地道的方式将执行TouchImageView的 setImage
方法,无需宽/高参数的。相反,它会推迟设置规模和矩阵,直到测量和实施 onMeasure
是这样的:
A more idiomatic approach would implement the setImage
method of TouchImageView without the width/height parameters at all. Instead it would defer setting the scale and matrices until measurement and implement onMeasure
something like this:
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
if (mNeedsInitialScale) { // Set by setImage when a new image is set
// The measured width and height were set by super.onMeasure above
setInitialScale(getMeasuredWidth(), getMeasuredHeight());
mNeedsInitialScale = false;
}
}
凡 setInitialScale
方法做的一切,在调用后链接 setImage
方法执行 super.setImageBitmap
。 setImage
还应设置 mNeedsInitialScale
字段设置为真
。
Where the setInitialScale
method does everything that the linked setImage
method does after the call to super.setImageBitmap
. setImage
should also set the mNeedsInitialScale
field to true
.
这样,你永远不需要担心初始大小使用,它会自动从过程中,每当一个新的图像设置正常测量查看得到。
This way you will never need to worry about the initial size to use, it will be obtained automatically from the View during normal measurement whenever a new image is set.
这篇关于如何找到的ImageView的宽度/高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!