drawInRect of UIImage is Not working

血红的双手。 提交于 2019-12-13 04:26:51

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!