[英]UIImageview won't center in superview
I have an UIImageView which I add to a UIView to enhance the area where touches are recognized. 我有一个UIImageView,我添加到UIView,以增强识别触摸的区域。 When I try to center the UIImageView in the UIView (code below) the center is set properly but when I run the program the image is shown way off outside the frame of the UIView.
当我尝试将UIImageView置于UIView(下面的代码)中心时,中心设置正确,但是当我运行程序时,图像显示在UIView框架之外。
Any ideas? 有任何想法吗?
// image size is 32x32 pixels but view will be created with 44x44 so touch recognition is better
self = [super initWithFrame:CGRectMake(position.x, position.y, 44, 44)];
if (self) {
switch (color) {
case Blue:
self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pin_red"]];
break;
case Green:
self.imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"pin_green"]];
default:
break;
}
[self setCenter:position];
[self addSubview:self.imageView];
[self setExclusiveTouch:YES];
[self setBackgroundColor:[UIColor clearColor]];
[self.imageView setCenter:position];
NSLog(@"uiview center: %@", NSStringFromCGPoint(self.center));
NSLog(@"image center: %@", NSStringFromCGPoint(self.imageView.center));
Thanks! 谢谢!
The imageview setCenter is relative to its parent. imageview setCenter相对于其父级。 Try:
尝试:
[self.imageView setCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2)];
UIImageView *imageforFace=[[UIImageView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width/2,[UIScreen mainScreen].bounds.size.height/2, 125,125)];
imageforFace.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
[imageforFace setCenter:CGPointMake(self.view.bounds.size.width/2, self.view.bounds.size.height/2)];
imageforFace.image=[UIImage imageNamed:@"face.png"];
[self.view addSubview:imageforFace];
Final the output is 最后输出是
try this code to give the UIImageView Frame Centre of UIView 尝试使用此代码来获取UIVmage的UIImageView框架中心
1) in .h file 1)在.h文件中
UIImageView *imgCenter;
2) in .m file 2)在.m文件中
- (void)viewDidLoad
{
imgCenter=[[UIImageView alloc]initWithFrame:CGRectMake([UIScreen mainScreen].bounds.size.width / 2, [UIScreen mainScreen].bounds.size.height / 2, 35, 35)];
[imgCenter setImage:[UIImage imageNamed:@"centerImage.png"]];
[self.view addSubview:imgCenter];
}
OR 要么
- (void)viewDidLoad
{
imgCenter=[[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 35, 35)];
imgCenter.center = self.view.center;
[imgCenter setImage:[UIImage imageNamed:@"centerImage.png"]];
[self.view addSubview:imgCenter];
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.