what is the difference between UIImageView and drawInRect?

旧巷老猫 提交于 2019-11-30 10:26:51

问题


I want to display so many images in table cells. I knew two methods to show an image.

One is creating an instance to UIImageView and show it

CGRect rect=CGRectMake(x,y,width,height);
UIImageView *image=[[UIImageView alloc]initWithFrame:rect];
[image setImage:[UIImage imageNamed:@"sample.jpg"]];

Another method is,

CGRect rect=CGRectMake(x,y,width,height);
[[UIImage imageNamed:@"sample.jpg"] drawInRect:rect];

Now, my question is, what is the difference between these two? Which one is efficient? Or someother function is available better than this?

Thanks in advance....


回答1:


Using the drawInRect: method has CoreGraphics draw the image into the active CGContext using the CPU. Assuming you're in a UIView's drawRect: method, this will paint the image into the view's buffer.

UIImageView uses whichever image is assigned to it as it's backing buffer instead of using the slower drawRect:. The GPU then references this buffer directly when the screen is composited via QuartzCore.




回答2:


UIImageView is a UIView subclass. By adding it to the view hierarchy you get all the free benefits: animations, size properties, affine transoforms, etc. Plus, you are able to change the underlying UIImage any time you want.

On the other hand, calling drawInRect: will just draw the image where you tell it to, but not interact with the UIView hierarchy, so you don't gain any of the benefits from having it on the view hierarchy.

I would think (have not tried it), that drawing the image directly is faster, but I would think in most of the cases having a UIImageView is a better idea.



来源:https://stackoverflow.com/questions/3838725/what-is-the-difference-between-uiimageview-and-drawinrect

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