UIImageview不会以superview为中心

时间:2012-11-07 13:45:56

标签: ios uiimageview center subview

我有一个UIImageView,我将其添加到UIView中以增强识别触摸的区域。当我尝试将UIImageView置于UIView(下面的代码)中心时,中心设置正确,但是当我运行程序时,图像显示在UIView框架之外。

有什么想法吗?

// 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));

谢谢!

3 个答案:

答案 0 :(得分:20)

imageview setCenter相对于其父级。尝试:

[self.imageView setCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2)];

答案 1 :(得分:1)

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];

最终输出

enter image description here

答案 2 :(得分:0)

尝试此代码以提供UIVmageView框架 UIView中心

1)在.h文件中

UIImageView *imgCenter;

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];
}

- (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];
}