【问题标题】:Why shadow radius also give effect on the inside of the circle?为什么阴影半径也会对圆的内部产生影响?
【发布时间】:2015-11-12 16:45:31
【问题描述】:

我想将阴影应用到圆圈的外层空间。但是阴影半径在内部也有影响,所以核心圆看起来比实际要小

我这样画圆:

self.shadowLayer = [CALayer layer];
self.shadowLayer.frame  = self.view.layer.bounds;
self.shadowLayer.shadowColor = [UIColor blueColor].CGColor;
self.shadowLayer.shadowRadius = 0;
self.shadowLayer.shadowOpacity = 1.0;
self.shadowLayer.shadowOffset = CGSizeMake(0,0);
CGRect frame = CGRectMake(0 , 50, self.view.bounds.size.width, self.view.bounds.size.width);
self.shadowLayer.shadowPath = [UIBezierPath bezierPathWithOvalInRect:CGRectInset(frame, 40, 40)].CGPath;
[self.view.layer addSublayer:self.shadowLayer];

结果是正常的圆:

但如果我将 self.shadowLayer.shadowRadius 从 0 更改为 30,结果是:

你可以看到,核心中纯色的尺寸缩小了。我希望该阴影仅在路径外部生效,并且纯色的大小与shadow radius = 0 的情况完全相同。截图后添加红色曲线。是不是只是为了看看大小的区别。

更新 一个想法是将shadowRadius 减少一半并将框架扩大相同的数量。我认为这已经足够好了。

【问题讨论】:

  • 尝试为阴影层提供 -40,-40 作为 cgrectinset
  • 它会太大。在这两种情况下,圆圈的框架应该保持不变。

标签: ios objective-c calayer shadow


【解决方案1】:

您可以使用NSShadow 并绘制自定义UIView 以产生您想要的效果。

用代码绘制自定义视图:

- (void)drawRect: (CGRect)frame
{
    //// General Declarations
    CGContextRef context = UIGraphicsGetCurrentContext();

    //// Color Declarations
    UIColor* color4 = [UIColor colorWithRed: 0.301 green: 0.261 blue: 0.968 alpha: 1];
    UIColor* shadowColor = [UIColor colorWithRed: 0 green: 0 blue: 0 alpha: 1];

    //// Shadow Declarations
    NSShadow* shadow = [[NSShadow alloc] init];
    [shadow setShadowColor: shadowColor];
    [shadow setShadowOffset: CGSizeMake(0.1, -0.1)];
    [shadow setShadowBlurRadius: 11];

    //// Oval Drawing
    UIBezierPath* ovalPath = [UIBezierPath bezierPathWithOvalInRect: CGRectMake(CGRectGetMinX(frame) + 69, CGRectGetMinY(frame) + 14, 72, 70)];
    CGContextSaveGState(context);
    CGContextSetShadowWithColor(context, shadow.shadowOffset, shadow.shadowBlurRadius, [shadow.shadowColor CGColor]);
    [color4 setFill];
    [ovalPath fill];
    CGContextRestoreGState(context);
}

在圆形边框外产生阴影效果:

【讨论】:

  • 如果您使用的是CGContextSetShadowWithColor,则不需要NSShadow。要使用后者,请调用-[NSShadow set] 方法。
  • 如果我们想存储引用并将其作为参数发送怎么办?我们还能用 cgcontextsetshadowwithcolor 做到这一点吗?
猜你喜欢
  • 2016-12-09
  • 2014-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-28
  • 2019-08-09
  • 2019-06-24
相关资源
最近更新 更多