核心图形的内部阴影

Ron*_*iew 3 cocoa-touch core-graphics ios

看到生成的代码用于绘制内部阴影.除了用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);
Run Code Online (Sandbox Code Playgroud)

小智 5

这里是PaintCode的开发者.

阴影偏移总是"舍入"到整数像素.不幸的是,Core Graphics存在某种精确/舍入问题.对于某些阴影偏移值,舍入会以某种方式消失并使用不正确的偏移量(例如,2而不是3).

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