Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UIImageview won't center in superview

I have an UIImageView which I add to a UIView to enhance the area where touches are recognized. 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.

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!

like image 475
illogic Avatar asked Nov 07 '12 13:11

illogic


1 Answers

The imageview setCenter is relative to its parent. Try:

[self.imageView setCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2)];
like image 78
tillerstarr Avatar answered Sep 28 '22 09:09

tillerstarr