向图层添加阴影会导致视网膜外观退化

sud*_*-rf 8 iphone cocoa-touch calayer ios

我有CALayer阴影的问题.以下是我的观点:

UIImage *screenshot = [SomeClass getScreenshot:mainView.view]; //full screen snap
CGFloat scale = [SomeClass getScreenScale]; // 1 or 2 for retina
CGFloat width = mainView.view.frame.size.width;
CGRect r1 = CGRectMake(0, 0, width*scale, 300*scale);     
CGRect u1 = CGRectMake(0, 0, width, 300);
CGImageRef ref1 = CGImageCreateWithImageInRect([screenshot CGImage], r1);
l1 = [[UIButton alloc] initWithFrame:u1];
UIImage *img1 = [UIImage imageWithCGImage:ref1];
[l1 setBackgroundImage:img1 forState:UIControlStateNormal];
[l1 setAdjustsImageWhenHighlighted:NO];
CGImageRelease(ref1);
[mainView.view addSubview:l1];
Run Code Online (Sandbox Code Playgroud)

好的,这样就可以了.添加的图像是视网膜分辨率.但是,只要我向图层添加阴影,它就会跳转到标准分辨率,使按钮显得模糊.

l1.layer.shadowOffset = CGSizeMake(0, 0);
l1.layer.shadowRadius = 20;
l1.layer.shadowColor = [UIColor blackColor].CGColor;
l1.layer.shadowOpacity = 0.8f;
l1.layer.shouldRasterize = YES;
Run Code Online (Sandbox Code Playgroud)

有没有理由为什么添加阴影会导致这个问题?

mar*_*cus 20

我不能说,为什么会发生,但我认为它是由UIImage创建引起的.你创建了一个大的(视网膜大小600*600像素)CGImageRef和UIImage.但UIImage并不知道,它是一个视网膜图像(它现在有600*600点,它应该有300*300点,比例因子2,这将再次产生600*600像素).

请尝试创建您的UIImage使用imageWithCGImage:scale:orientation:.这将使UIImage意识到视网膜尺度,并且图层操作可能正常.

所以你的路线是:

UIImage *img1 = [UIImage imageWithCGImage:ref1 
    scale: scale 
    orientation: UIImageOrientationUp];
Run Code Online (Sandbox Code Playgroud)

编辑(请参阅下面的评论):问题是由l1.layer.shouldRasterize = YES.您还需要指定l1.layer.rasterizationScale = scale并按预期渲染图像.

  • 我自己试了一下.造成错误的原因是l1.layer.shouldRasterize = YES; 您还需要设置l1.layer.rasterizationScale = scale. (12认同)