将 CGRect 在视图中居中
我有一个图像显示在 CGRect 中。如何使矩形在视图中居中?
这是我的代码:
UIImage * image = [UIImage imageNamed:place.image];
CGRect rect = CGRectMake(10.0f, 90.0f, image.size.width, image.size.height);
UIImageView * imageView = [[UIImageView alloc] initWithFrame:rect];
[imageView setImage:image];
我尝试过 imageView.center 但没有效果。
提前致谢。
I have an image displaying in a CGRect. how do I center the rect in the view?
here's my code:
UIImage * image = [UIImage imageNamed:place.image];
CGRect rect = CGRectMake(10.0f, 90.0f, image.size.width, image.size.height);
UIImageView * imageView = [[UIImageView alloc] initWithFrame:rect];
[imageView setImage:image];
I've tried imageView.center but to no effect.
thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(8)
查看:
https://developer.apple.com/documentation/coregraphics/cggeometry
你可以这样做:
Looking at:
https://developer.apple.com/documentation/coregraphics/cggeometry
You can do:
UIView 的
center
是一个属性,而不是一个方法。您需要计算要放置它的实际位置。您可以通过设置视图的框架或设置其中心来完成此操作,这在您的情况下更简单。
您没有说明然后将
imageView
设为哪个视图的子视图。如果您将其放入名为superview
的内容中,您可以这样做:UIView's
center
is a property, not a method.You need to calculate the actual location you want to put it in. You can do this by setting the frame of the view, or by setting its center, which is simpler in your case.
You don't say what view you then go make
imageView
a subview of. If you're putting it inside something calledsuperview
, you could do this:根据父视图矩形的大小和原点将 imageView 放置在父视图中。
给定一个名为parentView的父视图:
将原点转换为int可确保居中图像不模糊(尽管它可能会偏离中心一个子像素量)。
Position the imageView in the parentView based on the size and origin of the parentView's rect.
Given a parent view named parentView:
Casting the origins to int ensures that your centered image is not blurry (though it may be off center by a subpixel amount).
对于斯威夫特 4:
For Swift 4:
如果经常调用该函数,为了简单起见,您还可以使用此处所示的宏。
然后像这样使用它
If the function is called frequently, you can also use macros as shown here for simplicity.
Then use it like
雨燕4
Swift 4