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

时间:2011-06-04 08:06:12

标签: iphone cocoa-touch ios calayer

我遇到了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];

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

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;

添加阴影是否会导致此问题?

1 个答案:

答案 0 :(得分: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];

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