问题
I am Hardly Trying to learn New things with CoreGraphics. I have a the below code and the image is not set using drawInRect function.
- (void)viewDidLoad
{
[super viewDidLoad];
imgView=[[UIImageView alloc]init];
[self drawRect:CGRectMake(10, 10, 20, 20)];
}
- (void)drawRect:(CGRect)rect {
UIImage *img = [UIImage imageNamed:@"RoseBunch.jpeg"];
UIGraphicsBeginImageContext(CGSizeMake(320, 480));
[img drawInRect:CGRectMake(0, 0, 50, 50)];
UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
imgView.image=resultingImage;
}
Whats wrong in this? why its not working? can anyone explain me?
回答1:
The drawInRect method will work only on the current graphic context as written in the documentation.
The things is you are not drawing in the current graphic context since you use :
UIGraphicsBeginImageContext(CGSizeMake(320, 480));
I suggest you to try something like that :
UIImage *img = [UIImage imageNamed:@"RoseBunch.jpeg"];
CGContextRef c = UIGraphicsGetCurrentContext();
[img drawInRect:CGRectMake(0, 0, 50, 50)];
CGImageRef contextImage = CGBitmapContextCreateImage(c);
UIImage *resultingImage = [UIImage imageWithCGImage:contextImage];
imgView.image=resultingImage;
CGImageRelease(contextImage); //Very important to release the contextImage otherwise it will leak.
One more thing that is really important : You shouldn't load an Image in a draw method because the image will be load each time the draw function is called.
来源:https://stackoverflow.com/questions/14099778/drawinrect-of-uiimage-is-not-working