ios - 带有 Core Graphics 的内阴影

标签 ios cocoa-touch core-graphics

看到了绘制内部阴影的生成代码。除了使用 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);

最佳答案

PaintCode 的开发者|在这里。

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

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

关于ios - 带有 Core Graphics 的内阴影,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11085536/

相关文章:

iphone - 如何在UITextview/UILabel中使用自定义表情?

ios 无法更改 cellforrowatindexpath 中图像的角半径

iphone - XCode4 无法正确生成 NSManagedObject 子类

objective-c - 无需使用私有(private) API 即可获取当前第一响应者

ios - 画一个简单的圆uiimage

ios - 如何使用 SwiftUI 中的按钮在 View 之间导航?

ios - 存档验证错误 : Unsupported Architecture, 段对齐无效等 ~Jitsi Meet

ios - 更改标签栏导航 Controller 的根 Controller

Swift:覆盖方法具有不兼容的类型

iphone - CG上下文旋转