在方向更改时获取ImageView的宽度和高度(Get width and height of ImageView on orientation change)

编程入门 行业动态 更新时间:2024-10-25 20:17:37
在方向更改时获取ImageView的宽度和高度(Get width and height of ImageView on orientation change)

我正在尝试将位图放入ImageView中,以便在旋转设备时改变大小。 它会改变大小,因为我分别为纵向和横向模式加载不同的布局。 我根据ImageView放置在布局上时可用的屏幕空间大小来计算最终的位图大小。

目前我正试图通过自己处理配置更改(轮换)来解决这个问题。

我已经尝试使用onConfigurationChanged和ViewTreeObserver取得了一些成功。 只要我不使用setContentView,我就会获得ImageView的宽度和高度,并相应地进行缩放。 但是,我需要能够加载另一个布局并基于ImageView的可用空间,计算位图的新缩放。

我该如何做到这一点? 加载新布局后,ImageView的宽度和高度变为零。

我的目标是缩放位图大小以适应旋转时的imageview。

I'm trying to fit a bitmap into an ImageView that changes size when rotating the device. It changes size because I load different layouts for portrait and landscape mode respectively. I calculate the final bitmap size based on how much available screen space the ImageView has when it has been placed on the layout.

At the moment I'm trying to solve this by taking care of the configuration change (rotation) myself.

I have tried using onConfigurationChanged and ViewTreeObserver with some success. As long as I do not use setContentView I get width and height of the ImageView and the scaling is done accordingly. However, I need to be able to load another layout and based on the ImageView's available space, calculate a new scaling for the bitmap.

How do I accomplish this? As soon as I load a new layout, the width and height of the ImageView become zero.

My goal is to have the bitmap size scaled to fit the imageview on rotation.

最满意答案

您可以覆盖多种方法,包括onSizeChanged和onLayout,但所有这些方法都有怪癖。 我发现查找视图大小的最可靠方法是使用视图树观察器。 从观察者的视图中获得的宽度和高度可以更改,并且通常在更改全局映射时的第一次或前几次。

尝试在视图树观察器中记录onGlobalLayout中所需视图的宽度和高度,看看会发生什么。 还要确保在调用setContentView之后,再次调用findViewById以查找任何ImageView对象取代旧对象。 如果您仍然在旋转之前查看图像视图,则宽度和高度将永远不会准确,因为该视图不再处于任何可见布局中。

There are a variety of methods you can override including onSizeChanged and onLayout, but all of them have quirks. The most reliable way I've found to find out a views size is to use a view tree observer. The width and height you get from the view in the observer can change, and is often 0 the first or first several times onGlobalLayout is changed.

Try just logging the width and height of your desired view in onGlobalLayout in a view tree observer and see what happens. Also be sure that after you call setContentView, you call findViewById again to find whatever ImageView object takes the place of the old one. If you're still looking at the image view before the rotation, the width and height will never be accurate since that view is no longer in any visible layout.

更多推荐

本文发布于:2023-08-06 00:21:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1441146.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:宽度   高度   方向   ImageView   change

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!