CALayer renderInContext: Position of Drawing
Asked Answered
O

1

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.

Outreach answered 6/9, 2012 at 6:15 Comment(3)
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.Kovno
@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.Outreach
I discovered CGContextDrawLayer methods, which throw EXE_BAD_ACCESS when I try to use them.. I guess it's better to avoid those..Outreach
L
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.

Legibility answered 7/9, 2012 at 14:33 Comment(1)
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.Sophistication

© 2022 - 2024 — McMap. All rights reserved.