draw CALayer into a CGContext - calayer

I have the following code:
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CALayer *sublayer = [CALayer layer];
sublayer.backgroundColor = [UIColor orangeColor].CGColor;
sublayer.cornerRadius = 20.0;
sublayer.frame = CGRectMake(20, 0, 300, 20);
[sublayer setNeedsDisplay];
[sublayer drawInContext:context];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
But when i view the return newImage, there is just an empty image. When i change drawInContext to renderInContext, then i got the above sublayer, but it seems like the coordinate system is mess up.
Any idea why drawInContext on the above did not work?

Try using renderInContext in place of drawInContext.
My understanding is that drawInContext is there to be overridden, whereas renderInContext is used to render the contents of a layer to the context.
From the documentation:
- drawInContext:
The default implementation of this method does not doing any drawing itself. If the layer’s delegate implements the drawLayer:inContext: method, that method is called to do the actual drawing.
Subclasses can override this method and use it to draw the layer’s content. When drawing, all coordinates should be specified in points in the logical coordinate space.
- renderInContext:
This method renders directly from the layer tree, ignoring any animations added to the render tree. Renders in the coordinate space of the layer.

The coordinate system isn't messed up, per se. Quartz uses a different coordinate system than UIKit. In Quartz, the Y-axis originates at the bottom-left of the framing rectangle. The values become larger as you travel farther "up" the rectangle. For a visual representation, see the documentation at
http://developer.apple.com/library/mac/#documentation/graphicsimaging/Conceptual/drawingwithquartz2d/dq_overview/dq_overview.html
This differs from UIKit in that UIKit's coordinate system origin is the top-left with y-axis values becoming more positive as you travel "down".
As for why drawInContext: doesn't work, you should also reference the docs for the CALayer class where it says, "Default implementation does nothing."
http://developer.apple.com/library/mac/#documentation/GraphicsImaging/Reference/CALayer_class/Introduction/Introduction.html

Related

Apply NSAffineTransform to NSView

I want to do a couple of simple transforms on an NSView subclass to flip it on the X axis, the Y axis, or both. I am an experienced iOS developer but I just can't figure out how to do this in macOS. I have created an NSAffineTransform with the required translations and scales, but cannot determine how to actually apply this to the NSView. The only property I can find which will accept any kind of transform is [[NSView layer] transform], but this requires a CATransform3D.
The only success I have had is using the transform to flip the image if an NSImageView, by calling lockFocus on a new, empty NSImage, creating the transform, then drawing the unflipped image inside the locked image. This is far from satisfactory however, as it does not handle any subviews and is presumably more costly than applying the transform directly to the NSView/NSImageView.
This was the solution:
- (void)setXScaleFactor:(CGFloat)xScaleFactor {
_xScaleFactor = xScaleFactor;
[self setNeedsDisplay];
}
- (void)setYScaleFactor:(CGFloat)yScaleFactor {
_yScaleFactor = yScaleFactor;
[self setNeedsDisplay];
}
- (void)drawRect:(NSRect)dirtyRect {
NSAffineTransform *transform = [[NSAffineTransform alloc] init];
[transform scaleXBy:self.xScaleFactor yBy:self.yScaleFactor];
[transform set];
[super drawRect:dirtyRect];
}
Thank you to l'L'l for the hint about using NSGraphicsContext.
I can't believe how many hours of searching and experimenting I had to do before I was able to simply flip an image horizontally in AppKit. I cannot upvote this question and mashers' answer enough.
Here is an updated version of my solution for swift to flip an image horizontally. This method is implemented in an NSImageView subclass.
override func draw(_ dirtyRect: NSRect) {
// NSViews are not backed by CALayer by default in AppKit. Must request a layer
self.wantsLayer = true
if self.flippedHoriz {
// If a horizontal flip is desired, first multiple every X coordinate by -1. This flips the image, but does it around the origin (lower left), not the center
var trans = AffineTransform(scaledByX: -1, byY: 1)
// Add a transform that moves the image by the width so that its lower left is at the origin
trans.append(AffineTransform(translationByX: self.frame.size.width, byY: 0)
// AffineTransform is bridged to NSAffineTransform, but it seems only NSAffineTransform has the set() and concat() methods, so convert it and add the transform to the current graphics context
(trans as NSAffineTransform).concat()
}
// Don't be fooled by the Xcode placehoder. This must be *after* the above code
super.draw(dirtyRect)
}
The behavior of the transforms also took a bit of experimentation to understand. The help for NSAffineTransform.set() explains:
it removes the existing transformation matrix, which is an accumulation of transformation matrices for the screen, window, and any superviews.
This will very likely break something. Since I wanted to still respect all the transformations applied by the window and superviews, the concat() method is more appropriate.
concat() multiplies the existing transform matrix by your custom transform. This is not exactly cumulative, though. Each time draw is called, your transform is applied to the original transform for the view. So repeatedly calling draw doesn't continuously flip the image. Because of this, to not flip the image, simply don't apply the transform.

CATextLayer gets rasterized too early and it is blurred

I have some troubles with CATextLayer, that could be due to me, but I didn't find any help on this topic. I am on OS X (on iOS it should be the same).
I create a CATextLayer layers with scale factor > 1 and what I get is a blurred text. The layer is rasterized before applying the scale, I think. Is this the expected behavior? I hope it is not, because it just makes no sense... A CAShapeLayer is rasterized after that its transformation matrix is applied, why the CATextLayer should be different?
In case I am doing something wrong... what is it??
CATextLayer *layer = [CATextLayer layer];
layer.string = #"I like what I am doing";
layer.font = (__bridge CFTypeRef)[NSFont systemFontOfSize:24];
layer.fontSize = 24;
layer.anchorPoint = CGPointZero;
layer.frame = CGRectMake(0, 0, 400, 100);
layer.foregroundColor = [NSColor blackColor].CGColor;
layer.transform = CATransform3DMakeScale(2., 2., 1.);
layer.shouldRasterize = NO;
[self.layer addSublayer:layer];
The solution I use at the moment is to set the contentsScale property of the layer to the scale factor. The problem is that this solution doesn't scale: if the scale factor of any of the parent layers changes, then contentsScale should be updated too. I should write code to traverse the layers tree to update the contentsScale properties of all CATextLayers... not exactly what I would like to do.
Another solution, that is not really a solution, is to convert the text to a shape and use a CAShapeLayer. But then I don't see the point of having CATextLayers.
A custom subclass of CALayer could help in solving this problem?
EDIT: Even CAGradientLayer is able to render its contents, like CAShapeLayer, after that its transformation matrix is applied. Can someone explain how it is possible?
EDIT 2: My guess is that paths and gradients are rendered as OpenGL display lists, so they are rasterized at the actual size on the screen by OpenGL itself. Texts are rasterized by Core Animation, so they are bitmaps for OpenGL.
I think that I will go with the contentsScale solution for the moment. Maybe, in the future, I will convert texts to shapes. In order to get best results with little work, this is the code I use now:
[CATransaction setDisableActions:YES];
CGFloat contentsScale = ceilf(scaleOfParentLayer);
// _scalableTextLayer is a CATextLayer
_scalableTextLayer.contentsScale = contentsScale;
[_scalableTextLayer displayIfNeeded];
[CATransaction setDisableActions:NO];
After trying all the approaches, the solution I am using now is a custom subclass of CALayer. I don't use CATextLayer at all.
I override the contentsScale property with this custom setter method:
- (void)setContentsScale:(CGFloat)cs
{
CGFloat scale = MAX(ceilf(cs), 1.); // never less than 1, always integer
if (scale != self.contentsScale) {
[super setContentsScale:scale];
[self setNeedsDisplay];
}
}
The value of the property is always rounded to the upper integer value. When the rounded value changes, then the layer must be redrawn.
The display method of my CALayer subclass creates a bitmap image of the size of the text multiplied by the contentsScale factor and by the screen scale factor.
- (void)display
{
CGFloat scale = self.contentsScale * [MyUtils screenScale];
CGFloat width = self.bounds.size.width * scale;
CGFloat height = self.bounds.size.height * scale;
CGContextRef bitmapContext = [MyUtils createBitmapContextWithSize:CGSizeMake(width, height)];
CGContextScaleCTM(bitmapContext, scale, scale);
CGContextSetShouldSmoothFonts(bitmapContext, 0);
CTLineRef line = CTLineCreateWithAttributedString((__bridge CFAttributedStringRef)(_text));
CGContextSetTextPosition(bitmapContext, 0., self.bounds.size.height-_ascender);
CTLineDraw(line, bitmapContext);
CFRelease(line);
CGImageRef image = CGBitmapContextCreateImage(bitmapContext);
self.contents = (__bridge id)(image);
CGImageRelease(image);
CGContextRelease(bitmapContext);
}
When I change the scale factor of the root layer of my hierarchy, I loop on all text layers and set the contentsScale property to the same factor. The display method is called only if the rounded value of the scale factor changes (i.e. if the previous value was 1.6 and now I set 1.7, nothing happens. But if the new value is 2.1, then the layer is redisplayed).
The cost in terms of speed of the redraw is little. My test is to change continuously the scale factor of a hierarchy of 40 text layers on an 3rd gen. iPad. It works like butter.
CATextLayer is different because the underlying CoreText renders the glyphs with the specified font size (educated guess based on experiments).
You could add an action to the parent layer so as soon as it's scale changes, it changes the font size of the text layer.
Blurriness could also come from misaligned pixels. That can happen if you put the text layer to non integral position or any transformation in the superlayer hierarchy.
Alternatively you could subclass CALayer and then draw the text using Cocoa in drawInContext:
see example here:
http://lists.apple.com/archives/Cocoa-dev/2009/Jan/msg02300.html
http://people.omnigroup.com/bungi/TextDrawing-20090129.zip
If you want to have the exact behaviour of a CAShapeLayer then you will need to convert your string into a bezier path and have CAShapeLayer render it. It's a bit of work but then you will have the exact behaviour you are looking for. An alternate approach, is to scale the fontSize instead. This yields crisp text every time but it might not fit to you exact situation.
To draw text as CAShapeLayer have a look at Apple Sample Code "CoreAnimationText":
http://developer.apple.com/library/mac/#samplecode/CoreAnimationText/Listings/Readme_txt.html

OpenGL ES 1.1 iOS not sizing properly on retina versus non retina

So, I'm having quite a bizarre issue and I'm not sure why. When displaying the following opengl code on a retina screen, I receive the following image:
while the image I get on a non retina is the following:
The coordinate system should be setup normally.. I also noticed that it doesn't seem to generally scale to retina size. When getting the frame from the [UIScreen mainscreen], I'm getting the same value for both retina and non as shown below. Is there a special way I'm suppose to size this?
frame: Origin: x:0.000000 y:0.000000, Size: width:768.000000 height:1024.000000
*Edit: The cause was that OpenGL ES 1.1 does not scale to Retina size by itself. When creating the ViewPort you must manually scale the size as such glViewport(0, 0, width * [[UIScreen mainScreen] scale], height * [[UIScreen mainScreen] scale]);
This was the simplest method that I could come up with.*
OpenGL itself doesn't know anything about the view or screen characteristics; it only knows about the pixels.
By default, and unlike other UIViews, a GL-backed view will not automatically use non-1.0 scale, and will instead operate at 1x. So as you discovered, you should set the screen scale to opt in to the retina pixel resolution (which is 2x the size in both dimensions).
However, increasing the number of pixels just increases the number of pixels. GL doesn't then magically know that it's supposed to scale all of your geometry (or in fact that that's what you really want). If you want to use the same geometry for both scale views (which you usually do), then yes, you are also responsible for applying the scale.
In ES 1.1 (which you seem to be using, this is just:
glScalef([UIScreen mainScreen] scale], [UIScreen mainScreen] scale], 1.0);
In ES 2.0, you'd apply this to your model-view or projection matrix, which you then use in the vertex shader to transform your input geometry.
I found a 'scale' method for the view that apparently needs to be set to properly resize the view (as the view is position based rather pixel and for some bizarre reason, the positions don't resize with the increased resolution and such). This is the only thing I could really find. I've noted to include the following call check and set below within the init method of the GLView... but I'm still wondering if there's a better way. Wouldn't I manually have to resize everything by multiplying the height and width by the scale property?
- (id)initWithFrame:(CGRect)frame
{
NSLog(#"frame: Origin: x:%f y:%f, Size: width:%f height:%f", frame.origin.x, frame.origin.y, frame.size.width, frame.size.height);
self = [super initWithFrame:frame];
if (self) {
**if([[UIScreen mainScreen] respondsToSelector: NSSelectorFromString(#"scale")])
{
if([self respondsToSelector: NSSelectorFromString(#"contentScaleFactor")])
{
[self setContentScaleFactor:[[UIScreen mainScreen] scale]];
NSLog(#"Scale factor: %f", [[UIScreen mainScreen] scale]);
}
}**
NSLog(#"frame: Origin: x:%f y:%f, Size: width:%f height:%f Scale factor: %f", frame.origin.x, frame.origin.y, frame.size.width, frame.size.height, self.contentScaleFactor);
CAEAGLLayer *eaglLayer = (CAEAGLLayer *)super.layer;
eaglLayer.opaque = YES; // set to indicate that you do not need Quartz to handle transparency. This is a performance benefit.
context = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES1];
if (!context || ![EAGLContext setCurrentContext:context]) {
return nil;
}
That's the way I use setContentScaleFactor -- if you are on a retina device and you just want to render to the old non-retina resolution set that scale to 1 and iOS will double-size it for you.
Otherwise, if you write your code to detect retina devices and create a correspondingly larger viewport, setContentScaleFactor to 2 to be left alone by iOS.

How can I animate a UIBezierPath drawing to appear slowly as opposed to right away?

I'm writing an app (XCode 4.6) that displays drawings of various different paths - for now it's just straight lines and bezier paths, but eventually it will get more complicated. I am currently not using any layers and the display is actually pretty simple.
my drawRect code looks like this:
- (void)drawRect:(CGRect)rect :(int) points :(drawingTypes) type //:(Boolean) initial
{
//CGRect bounds = [[UIScreen mainScreen] bounds];
CGRect appframe= [[UIScreen mainScreen] applicationFrame];
CGContextRef context = UIGraphicsGetCurrentContext();
_helper = [[Draw2DHelper alloc ] initWithBounds :appframe.size.width :appframe.size.height :type];
CGPoint startPoint = [_helper generatePoint] ;
[_uipath moveToPoint:startPoint];
[_uipath setLineWidth: 1.5];
CGContextSetStrokeColorWithColor(context, [UIColor lightGrayColor].CGColor);
CGPoint center = CGPointMake(self.center.y, self.center.x) ;
[_helper createDrawing :type :_uipath :( (points>0) ? points : defaultPointCount) :center];
[_uipath stroke];
}
- (void)drawRect:(CGRect)rect
{
if (_uipath == NULL)
_uipath = [[UIBezierPath alloc] init];
else
[_uipath removeAllPoints];
[self drawRect:rect :self.graphPoints :self.drawingType ];
}
The actual path is generated by a helper object (_helper). I would like to animate the display of this path to appear slowly over a few seconds as it is being drawn - what is the easiest and fastest way of doing this?
What do you mean "appear slowly?" I assume you do not mean fade in all over at once, but rather mean that you want it to look like the path is being drawn with a pen?
To do that, do the following:
Create a CAShapeLayer the same size as your view and add it as a sublayer of your view.
Get the CGPath from your bezier path.
Install the CGPath into your shapeLayer.
Create a CABasicAnimation that animates the value of the shape layer's strokeEnd property from 0.0 to 1.0. That will cause the shape to be drawn as if it was being traced from beginning to end. You probably want a path that contains a single, contiguous sub-path. If you want it to circle back and connect, make it a closed path.
There are all kinds of cool tricks you can do with shape layers and animating changes to the path. and it's settings (like strokeStart and strokeEnd, stokeColor, fillColor, etc.) If you animate the path itself, you have to make sure the beginning path and ending path have the same number of control points internally. (And path arcs are tricky because the path has a different number of control points depending on the angle of the arc.)

Core animation geometry for layer-backed view

I have a layer-backed view, and want to understand how anchor point works for it and is it allowed at all to work with CALayer geometry properties (instead of using frame property of NSView)
First, quote from documentation:
The default value for anchorPoint is (0.5,0.5) which corresponds to
the center of the layer's bounds
But when I try to change value of anchor point to (0.5,0.5) directly, I got offset. Here is example, red area is the original position (when nothing applied to the anchor point), the button was moved to the bottom-left corner:
When I set anchor point to (0,0) button placed where it should be:
Update:
Here is the code I use to instantiate Button:
self.button = [[NSButton alloc] initWithFrame:NSMakeRect(130, 130, 100, 40)];
self.button.title = #"My Title";
self.button.wantsLayer = YES;
NSLog(#"Button anchor Point is : (%f;%f)", self.button.layer.anchorPoint.x, self.button.layer.anchorPoint.y);
[panelView addSubview:self.button];
What interesting, seems that for layer-backed view's the default anchor point is 0,0:
NSLog(#"Button anchor Point is : (%f;%f)", self.button.layer.anchorPoint.x, self.button.layer.anchorPoint.y);
produces (0.000000;0.000000)
After all, OS X Deployment target is 10.8
Here is quote from Apple documentation on NSView:
When using layer-backed views you should never interact directly with
the layer.
Seems this code cross the boundary of what you can do with layer-backed views.

Resources