【问题标题】:How to fix invalid context 0x0 with UIBezierPath?如何使用 UIBezierPath 修复无效的上下文 0x0?
【发布时间】:2014-10-07 11:23:02
【问题描述】:

我正在尝试找到实现圆角矩形的最佳方法(例如,像 iphone 图标一样闲逛)。我的搜索建议使用 UIBezierPath。

为了测试该类,我制作了一个新的 xcode 模板(单视图应用程序),基本上只是在 ViewController 的 viewDidLoad 中添加了以下几行:

UIBezierPath* path = [UIBezierPath
                      bezierPathWithRoundedRect: CGRectMake(10, 10, 120, 120)
                      cornerRadius: 5];
[[UIColor colorWithRed:0.5 green:0.5 blue:0.5 alpha:1.0] setFill];
[path stroke];
[path fill];

现在我收到几个“...invalid context 0x0 error...”。我假设我必须先设置一个上下文?!但是我该怎么做或者如果不解决这些错误呢?

我对该错误的搜索出现了一些帖子。不幸的是,它们似乎都具有相当复杂的相关编码。不过我很确定我在这里只是有一个非常基本的误解。

谢谢!

【问题讨论】:

标签: ios objective-c iphone xcode uibezierpath


【解决方案1】:

您可以使用它并在视图层中分配它

UIBezierPath *maskpath=[UIBezierPath bezierPathWithRoundedRect:view1.bounds
    byRoundingCorners:UIRectCornerBottomLeft|UIRectCornerBottomRight
     cornerRadii:CGSizeMake(10.0,10.0)];

   CAShapeLayer *maskLayer=[CAShapeLayer layer];

   maskLayer.frame=view1.bounds;

   maskLayer.path=maskpath.CGPath;

   [view1.layer addSublayer:maskLayer];

【讨论】:

  • 这是非常具有误导性的。您无需遮罩图层即可绘制圆角CAShapeLayer
  • 感谢您的快速回答!显然这个问题比我希望的要困难 - 我会尝试理解你的代码并报告......
  • @Desdenova 那么我们怎样才能使视图像圆角?
  • @johnykumar 将最后一行更改为[view.layer addSubLayer:yourShapeLayer],一切就绪。
  • @Desdenova 感谢您指导我。让我知道我是否正确。
【解决方案2】:

如果它对其他人有帮助:根据 johnykumar 提供的代码和关于类似主题的另一篇文章:

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor blackColor];
    CGRect frame = CGRectMake(50.0, 50.0, 150.0, 150.0);
    CGFloat radius = 20.0;
    UIView *frontView = [[UIView alloc] initWithFrame:frame];
    frontView.backgroundColor = [UIColor redColor];
    CAShapeLayer * maskLayer = [CAShapeLayer layer];
    maskLayer.path = [UIBezierPath bezierPathWithRoundedRect:frontView.bounds
                                           byRoundingCorners:UIRectCornerAllCorners
                                                 cornerRadii:CGSizeMake(radius,     radius)].CGPath;
    frontView.layer.mask = maskLayer;
    [self.view addSubview:frontView];
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-25
    • 2013-10-30
    • 2012-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多