【问题标题】:Inner shadow with Core Graphics带有核心图形的内阴影
【发布时间】:2012-06-18 15:00:20
【问题描述】:

看到了绘制内阴影的生成代码。除了使用 copysign 创建阴影的部分之外,一切都非常清楚和易于理解。

我了解 copysign 的作用,但为什么以及如何在下面的代码中实际使用它。

0.1 值对 xOffset 值似乎微不足道。

  CGContextRef context = UIGraphicsGetCurrentContext();
  
  UIColor *shadow = [UIColor redColor];
  CGSize shadowOffset = CGSizeMake(-2, -0);
  CGFloat shadowBlurRadius = 2;

  UIBezierPath *rectanglePath = [UIBezierPath bezierPathWithRect: CGRectMake(50, 50, 50, 50)];
  [[UIColor grayColor] setFill];
  [rectanglePath fill];
  
  CGRect rectangleBorderRect = CGRectInset([rectanglePath bounds], -shadowBlurRadius, -shadowBlurRadius);
  rectangleBorderRect = CGRectOffset(rectangleBorderRect, -shadowOffset.width, -shadowOffset.height);
  rectangleBorderRect = CGRectInset(CGRectUnion(rectangleBorderRect, [rectanglePath bounds]), -1, -1);
  
  UIBezierPath *rectangleNegativePath = [UIBezierPath bezierPathWithRect: rectangleBorderRect];
  [rectangleNegativePath appendPath: rectanglePath];
  rectangleNegativePath.usesEvenOddFillRule = YES;
  
  CGContextSaveGState(context);
  {
    CGFloat xOffset = shadowOffset.width + round(rectangleBorderRect.size.width);
    CGFloat yOffset = shadowOffset.height;
    CGContextSetShadowWithColor(context,
                                CGSizeMake(xOffset + copysign(0.1, xOffset), yOffset + copysign(0.1, yOffset)),
                                shadowBlurRadius,
                                shadow.CGColor);

    
    [rectanglePath addClip];
    CGAffineTransform transform = CGAffineTransformMakeTranslation(-round(rectangleBorderRect.size.width), 0);
    [rectangleNegativePath applyTransform: transform];
    [[UIColor grayColor] setFill];
    [rectangleNegativePath fill];
  }
  CGContextRestoreGState(context);

【问题讨论】:

    标签: ios cocoa-touch core-graphics


    【解决方案1】:

    PaintCode 的开发者在这里。

    阴影偏移总是“四舍五入”到整数像素。不幸的是,Core Graphics 中存在某种精度/舍入问题。对于某些阴影偏移值,舍入会以某种方式失效,并且使用了不正确的偏移(例如,2 而不是 3)。

    通过策略性地从阴影偏移中添加或减去 0.1,我们强制它始终正确运行。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-06
      • 1970-01-01
      • 1970-01-01
      • 2014-05-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多