Drawing a view hierarchy into a specific context in Cocoa - objective-c

For part of my application I have a need to create an image of a certain view and all of its subviews.
To do this I'm creating a context that wraps a bitmap with the same-size as the view, but I'm unsure how to draw the view hierarchy into it. I can draw a single view just be setting the context and explicitly calling drawRect, but this does not deal with all of the subviews.
I can't see anything in the NSView interface that could help with this so I suspect the solution may lie at a higher level.

I found that writing the drawing code myself was the best way to:
deal with potential transparency issues (some of the other options do add a white background to the whole image)
performance was much better
The code below is not perfect, because it does not deal with scaling issues when going from bounds to frames, but it does take into account the isFlipped state, and works very well for what I used it for. Note that it only draws the subviews (and the subsubviews,... recursively), but getting it to also draw itself is very easy, just add a [self drawRect:[self bounds]] in the implementation of imageWithSubviews.
- (void)drawSubviews
{
BOOL flipped = [self isFlipped];
for ( NSView *subview in [self subviews] ) {
// changes the coordinate system so that the local coordinates of the subview (bounds) become the coordinates of the superview (frame)
// the transform assumes bounds and frame have the same size, and bounds origin is (0,0)
// handling of 'isFlipped' also probably unreliable
NSAffineTransform *transform = [NSAffineTransform transform];
if ( flipped ) {
[transform translateXBy:subview.frame.origin.x yBy:NSMaxY(subview.frame)];
[transform scaleXBy:+1.0 yBy:-1.0];
} else
[transform translateXBy:subview.frame.origin.x yBy:subview.frame.origin.y];
[transform concat];
// recursively draw the subview and sub-subviews
[subview drawRect:[subview bounds]];
[subview drawSubviews];
// reset the transform to get back a clean graphic contexts for the rest of the drawing
[transform invert];
[transform concat];
}
}
- (NSImage *)imageWithSubviews
{
NSImage *image = [[[NSImage alloc] initWithSize:[self bounds].size] autorelease];
[image lockFocus];
// it seems NSImage cannot use flipped coordinates the way NSView does (the method 'setFlipped:' does not seem to help)
// Use instead an NSAffineTransform
if ( [self isFlipped] ) {
NSAffineTransform *transform = [NSAffineTransform transform];
[transform translateXBy:0 yBy:NSMaxY(self.bounds)];
[transform scaleXBy:+1.0 yBy:-1.0];
[transform concat];
}
[self drawSubviews];
[image unlockFocus];
return image;
}

You can use -[NSView dataWithPDFInsideRect:] to render the entire hierarchy of the view you send it to into a PDF, returned as an NSData object. You can then do whatever you wish with that, including render it into a bitmap.
Are you sure you want a bitmap representation though? After all, that PDF could be (at least in theory) resolution-independent.

You can use -[NSBitmapImageRep initWithFocusedViewRect:] after locking focus on a view to have the view render itself (and its subviews) into the given rectangle.

What you want to do is available explicitly already. See the section "NSView Drawing Redirection API" in the 10.4 AppKit release notes.
Make an NSBitmapImageRep for caching and clear it:
NSGraphicsContext *bitmapGraphicsContext = [NSGraphicsContext graphicsContextWithBitmapImageRep:cacheBitmapImageRep];
[NSGraphicsContext saveGraphicsState];
[NSGraphicsContext setCurrentContext:bitmapGraphicsContext];
[[NSColor clearColor] set];
NSRectFill(NSMakeRect(0, 0, [cacheBitmapImageRep size].width, [cacheBitmapImageRep size].height));
[NSGraphicsContext restoreGraphicsState];
Cache to it:
-[NSView cacheDisplayInRect:toBitmapImageRep:]
If you want to more generally draw into a specified context handling view recursion and transparency correctly,
-[NSView displayRectIgnoringOpacity:inContext:]

Related

Translating a view with a path (ObjectiveC, Cocoa)

The short story is that I would like the bounds (I think I mean bounds instead of frame) of a NSBezierPath to fill a view. Something like this:
To generate the above image I scaled/translated each point in my created path using the information from Covert latitude/longitude point to a pixels (x,y) on mercator projection. The problem is that this isn't scalable (I will be adding many more paths) and I want to easily add pan/zoom functionality to my view. Additionally, I want the stroke to remain the same regardless of scale (i.e. no fat boundaries when I zoom).
I think I want to generate a reusable path in some arbitrary reference frame (e.g. longitude and modified latitude) instead of generating a new path every time the window changes. Then I can translate/scale my view's coordinate system to fill the view with the path.
So I used Apple's geometry guide to to modify the view's frame. I got the translation right but scaling failed.
[self setBoundsOrigin:self.path.bounds.origin];
[self scaleUnitSquareToSize:NSMakeSize(1.5, 1.5)];
Then I tried a coordinate system transformation in my drawRect: method only to end up with a similar result.
NSAffineTransform* xform = [NSAffineTransform transform];
[xform translateXBy:(-self.path.bounds.origin.x) yBy:(-self.path.bounds.origin.y)];
[xform scaleXBy:1.5 yBy:1.5];
[xform concat];
Finally I tried manually setting the view bounds in drawRect: but the result was ugly and very slow!
I know I can also transform the NSBezierPath object and I think that would work, but I'd rather transform the view once instead of looping through and transforming each path every update. I think there's about three lines of code I'm missing that will do exactly what I'm looking for.
Edit:
Here's the drawRect: method I'm using:
- (void)drawRect:(NSRect)dirtyRect
{
// NSAffineTransform* xform = [NSAffineTransform transform];
// [xform translateXBy:-self.path.bounds.origin.x yBy:-self.path.bounds.origin.y];
// [xform scaleXBy:1.5 yBy:1.5];
// [xform concat];
[self drawBoundaries];
NSRect bounds = [self bounds];
[[NSColor blackColor] set];
[NSBezierPath fillRect:bounds];
// Draw the path in white
[[NSColor whiteColor] set];
[self.path stroke];
[[NSColor redColor] set];
[NSBezierPath strokeRect:self.path.bounds];
NSLog(#"path origin %f x %f",self.path.bounds.origin.x, self.path.bounds.origin.y);
NSLog(#"path bounds %f x %f",self.path.bounds.size.width, self.path.bounds.size.height);
}
I was able to get it to work using two transformations. I was trying to avoid this to reduce complexity and computation when I have many paths to transform and a window that zooms/pans.
- (void)transformPath:(NSBezierPath *)path
{
NSAffineTransform *translateTransform = [NSAffineTransform transform];
NSAffineTransform *scaleTransform = [NSAffineTransform transform];
[translateTransform translateXBy:(-self.path.bounds.origin.x)
yBy:(-self.path.bounds.origin.y)];
float scale = MIN(self.bounds.size.width / self.path.bounds.size.width,
self.bounds.size.height / self.path.bounds.size.height);
[scaleTransform scaleBy:scale];
[path transformUsingAffineTransform: translateTransform];
[path transformUsingAffineTransform: scaleTransform];
}

How to draw background image repeatedly with Mac OS

I am new in Mac OS programming. I would like to draw image repeatedly in background since my original image is small. Here is the code of drawing the image, but it seems enlarge the image which means it only draw one image instead of multiple.
// overwrite drawRect method of NSView
-(void)drawRect:(NSRect)dirtyRect{
[[NSImage imageNamed:#"imageName.png"] drawInRect:dirtyRect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1];
[super drawRect:dirtyRect];
}
This should work for you...
// overwrite drawRect method of NSView
-(void)drawRect:(NSRect)dirtyRect{
[super drawRect:dirtyRect];
// Develop color using image pattern
NSColor *backgroundColor = [NSColor colorWithPatternImage:[NSImage imageNamed:#"imageName.png"]];
// Get the current context and save the graphic state to restore it once done.
NSGraphicsContext* theContext = [NSGraphicsContext currentContext];
[theContext saveGraphicsState];
// To ensure that pattern image doesn't truncate from top of the view.
[[NSGraphicsContext currentContext] setPatternPhase:NSMakePoint(0,self.bounds.size.height)];
// Set the color in context and fill it.
[backgroundColor set];
NSRectFill(self.bounds);
[theContext restoreGraphicsState];
}
Note: You may like to consider creating backgroundColor as part of the object for optimization as drawRect is called pretty often.

Antialiased drawing in a CALayer

Greetings! I'm trying to draw a series of circles in a CALayer that resides in a zoomable UISCrollView. This is the layer that zooms on pinch. If i draw the circles using CAShapeLayer, then they zoom beautifully:
CAShapeLayer plotLayer = [CAShapeLayer layer];
plotLayer.bounds = self.bounds;
plotLayer.anchorPoint = CGPointZero;
plotLayer.position = CGPointZero;
CGMutablePathRef path = CGPathCreateMutable();
for (id one in many) {
CGRect ellipseRect = [one circleRect];
CGPathAddEllipseInRect(path, NULL, ellipseRect);
}
plotLayer.path = path
CFRelease(path);
[self.layer addSublayer:plotLayer];
[plotLayer setNeedsDisplay];
However, when i try to draw them with vanilla core graphics in my drawLayer:inContext: method, the circles get very jaggy (downright pro-aliased!) No amount of antialias jiggery-pokery seems to help:
-(void)drawLayer:(CALayer *)layer inContext:(CGContextRef)context
{
CGContextSetAllowsAntialiasing(context, true);
CGContextSetShouldAntialias(context, true);
CGContextClip(context);
for (id one in many) {
CGRect ellipseRect = [one circleRect];
CGContextStrokeEllipseInRect(context, ellipseRect);
}
}
I'm trying to figure out what CAShapeLayer is doing to get such nice antialiasing so that (aside from my own edification) i can take full advantage of core graphics in my drawing rather than just the stroke/fill that i can get with CAShapeLayer. Am i just missing a transform somewhere?
Many thanks!
Short answer: contentsScale
Longer answer: (taken almost verbatim from pe8ter at Vector like drawing for zoomable UIScrollView):
You can get a better rendering by setting the contentScale property on the layer in question after zooming:
- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView
withView:(UIView *)view
atScale:(float)scale
{
[CATransaction begin];
[CATransaction setValue:[NSNumber numberWithBool:YES]
forKey:kCATransactionDisableActions];
uglyBlurryTextLayer.contentsScale = scale;
[CATransaction commit];
}
There's a (typically excellent) description by Brad Larson of when the actual drawing occurs (spoiler, it usually only occurs once despite how many transforms are applied) at So a CALayer does not contain a content bitmap of a view?. Based on this, i can only assume that setting contentsScale causes the layer to render again.
I haven't tried this but if your circles get jaggy when resizing the view, it might be because of the interpolation quality.
Have you tried setting the interpolation quality to high?
CGContextSetInterpolationQuality(context, kCGInterpolationHigh);

Subclassing NSScrollView drawRect: Method

I'm customizing the UI for one of my apps, and the idea is that a text area is initially bordered gray when out of focus, and when it comes into focus, the border becomes bright white. My app uses a dark theme, and for a single-lined NSTextField, this works great.
I'm running into problems with a subclassed NSTextView, however. In order to alter the border properly, I ended up having to actually subclass the parent NSScrollView, but am still seeing strange behavior. (See screenshot below.) I want the red box to fill the entire scroll view, as this would allow me to stroke (instead of filling, which is just for testing) the path, producing a nice border. Instead, the red box seems to be only filling to the internal child view.
The following code snippet, which is for the NSScrollView subclass:
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
NSRect borderRect = self.bounds;
borderRect.origin.y += 1;
borderRect.size.width -= 1;
borderRect.size.height -= 4;
BOOL inFocus = ([[self window] firstResponder] == self);
if (!inFocus) {
inFocus = [self anySubviewHasFocus:self];
}
if (inFocus) {
[[NSColor colorWithDeviceRed:.8 green:.2 blue:0 alpha:1] set];
} else {
[[NSColor colorWithDeviceRed:.1 green:.8 blue:0 alpha:1] set];
}
[NSGraphicsContext saveGraphicsState];
[[NSGraphicsContext currentContext] setShouldAntialias:NO];
[NSBezierPath fillRect:borderRect];
[NSGraphicsContext restoreGraphicsState];
NSLog(#"My bounds: %#", NSStringFromRect(borderRect));
NSLog(#"Super (%#) bounds: %#", [self superview], NSStringFromRect(borderRect));
}
Produces the screenshot as seen below. Also, see the output in the log, which suggests that the entire view should be filled. This is the only output that is ever shown, regardless of the size of the text inside. Entering carriage returns increases the height of the red box, but does not produce different output. (And I would like the red box to fill the entire bounds.)
2011-04-08 21:30:29.789 MyApp[6515:903] My bounds: {{0, 1}, {196, 87}}
2011-04-08 21:30:29.789 MyApp[6515:903] Super (<EditTaskView: 0x3a0b150>) bounds: {{0, 1}, {196, 87}}
Edit: Thanks to Josh Caswell for his answer. See below for the proper behavior when not focused, and when focused.
As ughoavgfhw noted, NSScrollView doesn't usually do any drawing, and probably has a weird interaction with its child views in that way. I'd suggest putting something like the following in your text view's drawing code to draw this custom focus ring that you want*:
// We're going to be modifying the state for this,
// so allow it to be restored later
[NSGraphicsContext saveGraphicsState];
// Choose the correct color; isFirstResponder is a custom
// ivar set in becomeFirstResponder and resignFirstResponder
if( isFirstResponder && [[self window] isKeyWindow]){
[myFocusedColor set];
}
else {
[myNotFocusedColor set];
}
// Create two rects, one slightly outset from the bounds,
// one slightly inset
NSRect bounds = [self bounds];
NSRect innerRect = NSInsetRect(bounds, 2, 2);
NSRect outerRect = NSMakeRect(bounds.origin.x - 2,
bounds.origin.y - 2,
bounds.size.width + 4,
bounds.size.height + 4);
// Create a bezier path using those two rects; this will
// become the clipping path of the context
NSBezierPath * clipPath = [NSBezierPath bezierPathWithRect:outerRect];
[clipPath appendBezierPath:[NSBezierPath bezierPathWithRect:innerRect]];
// Change the current clipping path of the context to
// the enclosed area of clipPath; "enclosed" defined by
// winding rule. Drawing will be restricted to this area.
// N.B. that the winding rule makes the order that the
// rects were added to the path important.
[clipPath setWindingRule:NSEvenOddWindingRule];
[clipPath setClip];
// Fill the rect; drawing is clipped and the inner rect
// is not drawn in
[[NSBezierPath bezierPathWithRect:outerRect] fill];
[NSGraphicsContext restoreGraphicsState];
This should be a reasonable approximation of what AppKit does when it draws a focus ring. Of course, AppKit is sort of allowed to draw outside a view's bounds -- I can't guarantee that this is completely safe, but you seem to get a margin of 3 px to play with. You could draw the ring entirely inside the bounds if you wanted. A true focus ring extends slightly (2 px) inside the view anyways (as I've done here).
Apple docs on Setting the Clipping Region.
EDIT: After re-reading your comments on the question, I realize I may have long-winded-ly buried the real answer. Try either subclassing NSClipView and switching your scroll view's clip view for that, or using a custom view for the document view.
*: You could also put this in the drawing code of a custom view subclass which is set as the document view of the NSScrollView; then your text view could be a subview of that. Or substitute a custom NSClipView subclass.

NSBitmapImageRep and multi-page TIFFs

I've got a program that can open TIFF documents and display them. I'm using setFlipped:YES.
If I'm just dealing with single page image files, I can do
[image setFlipped: YES];
and that, in addition to the view being flipped, seems to draw the image correctly.
However, for some reason, setting the flipped of the image doesn't seem to affect the flippedness of the individual representations.
This is relevant because the multiple images of a multi-page TIFF seem to appear as different "representations" of the same image. So, if I just draw the IMAGE, it's flipped, but if I draw a specific representation, it isn't flipped. I also can't seem to figure out how to chose which representation is the default one that gets drawn when you draw the NSImage.
thanks.
You shouldn't use the -setFlipped: method to control how the image is drawn. You should use a transform based on the flipped-ness of the context you are drawing into. Something like this (a category on NSImage):
#implementation NSImage (FlippedDrawing)
- (void)drawAdjustedInRect:(NSRect)dstRect fromRect:(NSRect)srcRect operation:(NSCompositingOperation)op fraction:(CGFloat)delta
{
NSGraphicsContext* context = [NSGraphicsContext currentContext];
BOOL contextIsFlipped = [context isFlipped];
if (contextIsFlipped)
{
NSAffineTransform* transform;
[context saveGraphicsState];
// Flip the coordinate system back.
transform = [NSAffineTransform transform];
[transform translateXBy:0 yBy:NSMaxY(dstRect)];
[transform scaleXBy:1 yBy:-1];
[transform concat];
// The transform above places the y-origin right where the image should be drawn.
dstRect.origin.y = 0.0;
}
[self drawInRect:dstRect fromRect:srcRect operation:op fraction:delta];
if (contextIsFlipped)
{
[context restoreGraphicsState];
}
}
- (void)drawAdjustedAtPoint:(NSPoint)point
{
[self drawAdjustedAtPoint:point fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
}
- (void)drawAdjustedInRect:(NSRect)rect
{
[self drawAdjustedInRect:rect fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0];
}
- (void)drawAdjustedAtPoint:(NSPoint)aPoint fromRect:(NSRect)srcRect operation:(NSCompositingOperation)op fraction:(CGFloat)delta
{
NSSize size = [self size];
[self drawAdjustedInRect:NSMakeRect(aPoint.x, aPoint.y, size.width, size.height) fromRect:srcRect operation:op fraction:delta];
}
#end
I believe that the answer is that Yes, different pages are separate representations, and the correct way to deal with them is to turn them into images with:
NSImage *im = [[NSImage alloc] initWithData:[representation TIFFRepresentation]];
[im setFlipped:YES];