I make my own UIImageView, like this:
@interface MyImageView : UIImageView{
}
And I have the initWithFrame like this:
- (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;
}
I want to change the image when the user touchesBegin, so I have something like this:
- (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);
}
I find that I can't change the image. So, I add a line [self addS开发者_如何学运维ubview:imageView]; in the touchesBegan method, that's work. But I have no idea on why I can't change the image from the touchesBegan, thz.
Why are you returning void
from initWithFrame
??
You should return the initialized object from 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;
}
精彩评论