【问题标题】:CALayer renderInContext: Position of DrawingCALayer renderInContext:绘图的位置
【发布时间】:2012-09-06 06:15:09
【问题描述】:

我有一个UIView,在drawRect: 中绘制了一个自定义形状。 frame 属性设置为:

{5.f, 6.f, 50.f, 50.f}

现在,我在 Image Context 中渲染视图,但它忽略了 UIView 的 frame 属性,并始终在左上角绘制 UIView

[_shapeView.layer renderInContext:UIGraphicsGetCurrentContext()];

我尝试更改CALayerframe,但没有任何改变。修改 bounds 属性让事情变得更糟。我发现唯一有用的解决方法是:

CGRect frame = _shapeView.frame;
CGContextTranslateCTM(context, frame.origin.x, frame.origin.y);
[_shapeView.layer renderInContext:context];

但是,当我处理许多形状时,这是不切实际的,我只想使用 frame 属性。

【问题讨论】:

  • 预计会发生这种情况。想一想,如果相反的情况属实,那将意味着什么。无论如何,请尝试更改 bounds 的来源。
  • @DavidRönnqvist 谢谢,更改边界会导致绘图的上 6 px 和左 5 px 被切片 :( ,即不起作用。
  • 我发现了 CGContextDrawLayer 方法,当我尝试使用它们时会抛出 EXE_BAD_ACCESS。我想最好避免使用这些方法。

标签: core-animation calayer drawrect cgcontext


【解决方案1】:

使用CGContextTranslateCTM 是正确的方法。正如renderInContext: documentation 所说:“在图层的坐标空间中渲染。”这意味着您的图层/视图的框架原点被忽略。

关于CGContextDrawLayer,它不是用于CALayer,而是用于CGLayer。这是两个非常不同的事情,并解释了您的崩溃。

【讨论】:

  • 在调用-renderInContext:之前对上下文的其他修改也有很好的提示!所以方法是先准备好你的上下文,然后再渲染它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-24
  • 1970-01-01
相关资源
最近更新 更多