CALayer和Retina显示屏的高分辨率的支持

来源:互联网 发布:淘宝直播红包雨怎么玩 编辑:程序博客网 时间:2024/05/16 15:35

    最近在做ios应用的时候遇到一个非常棘手的bug,花了我一整天的时间,所以特别想写出来分享给其他程序员。

    这个bug源于一个用UIView对象生成显示的UIImage对象之后,把这个UIImage对象设置到另一个view的layer中.

    上代码:

(1)UIView生成UIImage代码:

#import <QuartzCore/QuartzCore.h>
-(UIImage *)getImageFromView:(UIView *)orgView{
    UIGraphicsBeginImageContext(orgView.bounds.size);
    [orgView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

 (2)UIImage设置到另一个view的layer:

CALayer *lay = [CALayer layer];

UIView *showImage = [getImageFromView:showView];//调用上面的获取view的image的方法

lay.contents = showImage;

otherView.layer = lay;


只后显示代码发现,在普通320*480分辨率屏幕上显示完全没有问题,但是在retina的高分辨率下却显示会显示出非常模糊的图片。

找了很多文件,终于发现QuartzCore和CALayer对高分辨率的支持的方法。

直接上解决办法代码:

(1)UIView生成UIImage代码:

#import <QuartzCore/QuartzCore.h>
-(UIImage *)getImageFromView:(UIView *)orgView{

    if(UIGraphicsBeginImageContextWithOption!=nil){
   UIGraphicsBeginImageContextWithOptions(orgView.bounds.size, NO, 1.0);;

    }else{

    UIGraphicsBeginImageContext(orgView.bounds.size);

    }
    [orgView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

 (2)UIImage设置到另一个view的layer:

CALayer *lay = [CALayer layer];

UIView *showImage = [getImageFromView:showView];//调用上面的获取view的image的方法

lay.contentsScale = 2.0f;

lay.contents = showImage;

otherView.layer = lay;


因为开始接触这个问题的时候,对CALayer和UIView的关系不够清楚,对CALayer的了解也不够清楚;加上网上并没有很多关于这个问题的资料,所以花了很多时间都没有想到这个点上,导致浪费了很多时间。再次给ios程序员奉上此文,希望遇到类似问题的朋友一个参考,希望其他人不要再像我这样浪费这么多时间了。

另外,以上代码是我记得的代码,并不是直接在项目上考下来的代码,如果有问题,请细心调试,但是contentScale的和UIGraphicsBeginImageContextWithOptions的知识点是没有问题的。


原创粉丝点击