为什么我无法更新我的UIImageView?

时间:2010-05-03 16:14:07

标签: iphone objective-c uiimageview

我制作了自己的UIImageView,如下所示:

@interface MyImageView : UIImageView{


}

我有这样的initWithFrame:

- (id)initWithFrame{
    if( ( self = [ super initWithFrame: CGRectMake(0, 0, 175, 175) ] ) ) {

    UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"myImage" ofType:@"png"]];
    CGRect cropRect = CGRectMake(175, 0, 175, 175);
    CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], cropRect);   
    //self = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 175, 175)];
    //self.image = [UIImage imageWithCGImage:imageRef];
    [self setImage:[UIImage imageWithCGImage:imageRef]];


    CGImageRelease(imageRef);
    }
    return self;

}

我想在用户触摸开始时更改图像,所以我有这样的事情:

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

   UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle] pathForResource:@"myImage2" ofType:@"png"]];
    CGRect cropRect = CGRectMake(0, 0, 175, 175);
    CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], cropRect);   
    //self = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 175, 175)];
    [self setImage:[UIImage imageWithCGImage:imageRef]];
    CGImageRelease(imageRef);
}

我发现我无法改变图像。所以,我添加一行[self addSubview:imageView];在touchesBegan方法中,这是有效的。但是我不知道为什么我不能改变touchesBegan中的图像。

1 个答案:

答案 0 :(得分:1)

为什么要从void ??

返回initWithFrame

您应该从initWithFrame返回初始化对象。

- (id)initWithFrame{    
   if( ( self = [ super initWithFrame: CGRectMake(0, 0, 175, 175) ] ) ) {
       UIImage *img = [UIImage imageWithContentsOfFile: [[NSBundle mainBundle]      pathForResource:@"myImage" ofType:@"png"]];
       CGRect cropRect = CGRectMake(175, 0, 175, 175);
       CGImageRef imageRef = CGImageCreateWithImageInRect([img CGImage], cropRect);   
       self.image = [UIImage imageWithCGImage:imageRef];
       [self addSubview:imageView];
       CGImageRelease(imageRef);
   }
   return self;
}