ios - 使用 bezierPathWithOvalInRect 绘制时边框被剪裁

标签 ios objective-c uikit drawrect uibezierpath

我在自定义 UIView 的 drawRect 中画了一个圆:

- (void)drawRect:(CGRect)rect {
  ...
  UIBezierPath *ovalPath = [UIBezierPath bezierPathWithOvalInRect:rect];
  [UIColor.whiteColor setStroke];
  ovalPath.lineWidth = 1;
  [ovalPath stroke];
}

椭圆总是在边缘被剪裁。我怎样才能避免剪裁?插入矩形是唯一的方法吗?

最佳答案

CG 以路径为中心绘制笔划——一半在路径内,一半在路径外。因此,部分中风在您的视野之外,您看不到它。

将矩形插入笔画宽度的一半。

CGRect rectToStroke = CGRectInset(rect, 0.5, 0.5);
UIBezierPath *ovalPath = [UIBezierPath bezierPathWithOvalInRect: rectToStroke];

您使用 CG 或 UIKit 在 -drawRect: 中绘制的任何内容都会进入一个位图上下文,该上下文是您 View 的 bounds 的大小。

如果您需要显示大于 bounds.size 的内容,您有两个选择:使 View 的 bounds 更大,或者通过其他方法绘制,例如:

  1. 添加一个更大的 subview (但它会出现在您的 View 顶部,因此您需要使其部分透明)
  2. CALayerCAShapeLayer 添加到您的 View 层(具有相同的警告)
  3. 设置 View 层的 borderWidth 以在内容顶部绘制边框

(对于所有这些,您可能会发现还需要将 View 的 clipsToBounds 属性设置为 NO,如果尚未设置的话。)

关于ios - 使用 bezierPathWithOvalInRect 绘制时边框被剪裁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35109378/

相关文章:

android - 您可以将 Apple 的 mapkit 用于混合应用程序吗?

ios - 如何以编程方式在 SQLite 中创建多个表,即;通过 ios 中的代码

iPhone:如何使用 NSUserDefaults 存储 UIImage?

iphone - iOS:ASIHTTPRequest 在后台选择器上同步是个坏主意吗?

ios - 如何在 ios 中捕获数据库异常?

ios - webview 在 objective-c 中不起作用

ios - 插入多个字符时关闭文本字段

ios - 在 iOS 上学习编码——swift 与 Objective C 的困境

iOS: UIView 子类 init 或 initWithFrame:?

iphone - CALayer 性能与 UIImageView 性能