[英]Swift programmatically place UIImageView on top of another and resize
On my storyboard I have 2 image views. 在我的故事板上,我有2个图像视图。 One holds the main image, the second is an overlay which will be used to specify the crop area of the main image.
一个保存主图像,第二个是覆盖图,用于指定主图像的裁剪区域。
In my viewDidLoad I've done this. 在我的viewDidLoad中我做到了这一点。
let screen_width = UIScreen.mainScreen().bounds.width
let screen_height = UIScreen.mainScreen().bounds.height
self.overlayImage.frame = CGRect(x: self.imageView.frame.origin.x, y: self.imageView.frame.origin.y, width: screen_width, height: (screen_height * 0.1919))
The goal is to have the overlayImage's top left corner lined up properly with the imageView's top left corner. 目标是使overlayImage的左上角与imageView的左上角正确对齐。 Also the height of the overlay should be about 1/5th of the screens size.
覆盖层的高度也应约为屏幕尺寸的1/5。 However when I run the code the overlayImage is exactly the same size and in the same location it was originally on the storyboard.
但是,当我运行代码时,overlayImage的大小完全相同,并且位于故事板上最初的位置。
How can I programmatically line it up on top of the imageView after the image has been set to it, and also resize the overlayImage dynamically in the viewDidload? 如何在将图像设置为imageView之后以编程方式将其排列在imageView之上,还可以在viewDidload中动态调整overlayImage的大小? I'd just do it manually in storyboard editor but everyone will have different screen sizes so I thought it best to use the mainscreen().bounds.height variable to determine the amount of height to use dynamically at runtime.
我只是在storyboard编辑器中手动完成,但每个人都有不同的屏幕尺寸,所以我认为最好使用mainscreen()。bounds.height变量来确定在运行时动态使用的高度。
All you have to do is to write your above code in viewDidAppear
instead of viewDidLoad
as below:- 您所要做的就是在
viewDidAppear
而不是viewDidLoad
编写您的上述代码,如下所示: -
override func viewDidAppear(animated: Bool) {
let screen_width = UIScreen.mainScreen().bounds.size.width
let screen_height = UIScreen.mainScreen().bounds.size.height
self.overlayImage.frame = CGRect(x: 0, y: 0, width: screen_width, height:screen_height/5)
}
And your frame will set itself as desired. 你的框架将根据需要设置自己。
Since you're working with Storyboard, I would rather use Autolayout and Constraints to solve this problem for me... For instance you set the constraints for your first image view, then set the constraints of your overlay based and related to the former one. 由于您正在使用Storyboard,我宁愿使用Autolayout和Constraints为我解决这个问题...例如,您为第一个图像视图设置了约束,然后设置基于叠加的约束并与前一个相关。 Example:
例:
Thus, when ever the screen size changes, the two images will always resize equally... 因此,当屏幕尺寸发生变化时,两个图像将始终同等地调整大小......
Interface builder: 界面构建器:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.