16

I have a UIView with a custom shape drawn in drawRect:. The frame property is set to:

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

Now, I render the view in an Image Context, but it is ignoring the frame property of the UIView, and always drawing the UIView in the top left.

[_shapeView.layer renderInContext:UIGraphicsGetCurrentContext()];

I tried to change the frame of the CALayer, but nothing changed. Modifying the bounds property made things worse. The only work around I found useful was:

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

But, this is impractical when I am dealing with many shapes, I want to just use the frame property.

Mazyod
  • 22,319
  • 10
  • 92
  • 157
  • That is expected to happen. Think of what it would mean if the opposite was true. Anyhow, try changing the origin of the `bounds` instead. – David Rönnqvist Sep 06 '12 at 06:52
  • @DavidRönnqvist Thanks, changing the bounds would cause the upper 6 px and left 5 px of the drawing to be sliced :( , ie doesn't work. – Mazyod Sep 06 '12 at 07:10
  • I discovered `CGContextDrawLayer` methods, which throw EXE_BAD_ACCESS when I try to use them.. I guess it's better to avoid those.. – Mazyod Sep 06 '12 at 07:12

1 Answers1

31

Using CGContextTranslateCTM is the proper way to go. As renderInContext: documentation states : "Renders in the coordinate space of the layer." This means the frame origin of your layer/view is ignored.

Regarding CGContextDrawLayer, it is not made to be used with CALayer, but with CGLayer. These are two very different things, and explains your crash.

amadour
  • 1,600
  • 11
  • 20
  • Great hint also for other modifications of the context before calling `-renderInContext:`! So the way is to prepare your context first and render to it afterwards. – Lukáš Kubánek Mar 27 '14 at 13:28