2

我正在使用带有路径的 CAShapeLayer。现在我希望它投射出大约 10 个单位厚度的平滑阴影。

第一:是的,我可以只创建 11 个 CAShapeLayer 对象,并且每次将路径的轮廓增加 1 个单位,并在每次迭代时使用不同的颜色和更多的 alpha。但是这样我就炸毁了我的内存占用,因为它是屏幕大小的一半,这意味着内存中有 11 倍的半屏幕大小的位图。

因此,从 iPhone OS 3.2 开始,我可能可以在 CALayer 上使用那些漂亮的阴影属性。但我想坚持使用 OS 3.0。那么除了上面那个讨厌的选项,我还有什么选择呢?

4

1 回答 1

0

您可以使用 Core Graphics 创建阴影。QuartzDemo示例中描述了您需要的构建块。特别是class QuartzMaskingViewQuartzClipping.m中查看。

  1. 将形状图层的内容捕获到图像中
  2. 根据自己的喜好设置阴影
  3. 开始透明层
  4. 剪辑到图层内容的图像 - 您将在它之外绘图
  5. 再次绘制您的图像

这会导致在蒙版区域之外绘制阴影。

CGSize size = CGSizeMake(300, 100);

UIGraphicsBeginImageContextWithOptions(size,NO, 0.0);
[shapeLayer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

CGRect flippedImageRect = 
    CGRectMake(0, 0, image.size.width, -image.size.height);

CGContextRef ctx = UIGraphicsGetCurrentContext();
CGContextSaveGState(ctx);
CGContextSetShadowWithColor(ctx, CGSizeMake(4, 4), 2, 
    [[UIColor colorWithWhite:0 alpha:0.4] CGColor]);
CGContextBeginTransparencyLayer(ctx, NULL);
CGContextScaleCTM(ctx, 1.0, -1.0);
CGContextClipToMask(ctx, flippedImageRect, [image CGImage]);   
CGContextSetFillColorWithColor(ctx, [[UIColor redColor] CGColor]); 
CGContextDrawImage(ctx, flippedImageRect, [image CGImage]);
CGContextEndTransparencyLayer(ctx);
CGContextRestoreGState(ctx);
于 2011-05-19T00:02:51.230 回答