简体   繁体   中英

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!

The imageview setCenter is relative to its parent. 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

1) in .h file

UIImageView *imgCenter;

2) in .m file

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM