UIImage的drawInRect无法正常工作 [英] drawInRect of UIImage is Not working

查看:103
本文介绍了UIImage的drawInRect无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我几乎不尝试通过CoreGraphics学习新事物。我有下面的代码,并且没有使用drawInRect函数设置图像。

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?

推荐答案

drawInRect方法仅在当前图形上下文中有效,如文档

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.

还有一件很重要的事情:您不应该在draw方法中加载Image,因为每次调用draw函数时都会加载图像。

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.

这篇关于UIImage的drawInRect无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆