如何找到 ImageView 的宽度/高度?
我的问题类似于这个问题。我已经使用 此代码 来扩展 ImageView 以形成 TouchImageView 。在我的 onCreate() 方法中,我想调用
setImage(Bitmap bm, int displayWidth, int displayHeight)
但不知道要使用的宽度或高度。当我调用 getHeight() 时,它给我零。
我尝试使用 kcoppock 对 之前提到的问题,但没有成功。 onPreDraw() 监听器每秒被调用几次,我不知道如何只调用它一次。
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)
but I don't know the width or height to use. When I call getHeight(), it gives me zero.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
对于这样的事情来说,这是一种脆弱的方法。 Android View 通过其父 View 使用
onMeasure
方法进行测量。通过向setImage
方法提供初始大小以进行缩放(特别是如果您根据显示大小设置它),每当您想要将此 View 嵌套在其他 View 中时,都会带来复杂性。平板电脑等大屏幕设备就是一个很好的例子。更惯用的方法是实现 TouchImageView 的 setImage 方法,而无需宽度/高度参数。相反,它会推迟设置比例和矩阵,直到测量并实现
onMeasure
,如下所示:其中
setInitialScale
方法执行链接的setImage
方法的所有操作在调用super.setImageBitmap
之后执行。setImage
还应将mNeedsInitialScale
字段设置为true
。这样您就永远不需要担心要使用的初始尺寸,每当设置新图像时,在正常测量期间都会自动从视图中获取它。
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 asetImage
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.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 implementonMeasure
something like this:Where the
setInitialScale
method does everything that the linkedsetImage
method does after the call tosuper.setImageBitmap
.setImage
should also set themNeedsInitialScale
field totrue
.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.
ImageViews 尺寸为 0,直到您的 Activity 将其绘制在屏幕上。您可以使用 Activitys onFocusChanged 来设置位图并获取正确的尺寸
如果您只是寻找 DisplayWidth 和 height,您可以致电
并向 Display 询问其尺寸
the ImageViews dimensions are 0 until your Activity draw it on the screen. You could use Activitys onFocusChanged to set the Bitmap and get correct Dimensions
if you are just looking for DisplayWidth and height you can call
and ask Display for its dimensions