6

我有一个 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));

谢谢!

4

3 回答 3

21

imageview setCenter 是相对于它的父级的。尝试:

[self.imageView setCenter:CGPointMake(self.bounds.size.width/2, self.bounds.size.height/2)];
于 2012-11-07T13:53:11.287 回答
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];

最终输出是

在此处输入图像描述

于 2015-05-28T14:41:03.817 回答
0

试试这段代码给UIView 的 UIImageView Frame Center

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];
}
于 2014-12-02T13:33:26.203 回答