我制作了自己的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中的图像。
答案 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;
}