I am drawing several CGPaths in a Cocoa view in the drawRect method on an iPad. I started out drawing them straight to the UIGraphicsGetCurrentContext() context, but performance went south when my paths got really long. Based on several other questions, I started looking into using CGLayers.
So what I do now is to render a path inside of the CGContextRef I get from calling CGLayerGetContext. Here's the basic outline of what I'm doing:
// rect comes from the drawRect: method
layer = CGLayerCreateWithContext(context, rect.size, NULL);
layerContext = CGLayerGetContext(layer);
CGContextSetLineCap(layerContext, kCGLineCapRound);
// Set the line styles
CGContextSetLineJoin(layerContext, kCGLineJoinRound);
CGContextSetLineWidth(layerContext, 1.0);
CGContextSetStrokeColorWithColor(layerContext, [UIColor blackColor].CGColor);
// Create a mutable path
path = CGPathCreateMutable();
// Move to start point
//...
for (int i = 0; i < points.count; i++) {
// compute controlPoint and anchorPoint
//...
CGPathAddQuadCurveToPoint(path,
nil,
controlPoint.x,
controlPoint.y,
anchorPoint.x,
anchorPoint.y);
}
// Stroke the path
CGContextAddPath(layerContext, path);
CGContextStrokePath(layerContext);
// Add the layer to the main context
CGContextDrawLayerAtPoint(context, CGPointZero, layer);
Now, I get good performance drawing, but my lines are extremely jagged and do not seem to be anti-aliased. I've tried adding
CGContextSetShouldAntialias(layerContext, YES);
CGContextSetAllowsAntialiasing(layerContext, YES);
CGContextSetInterpolationQuality(layerContext, kCGInterpolationHigh);
to the code above to no avail. I've even set the anti-aliasing properties on the main context, with no change. I took screen shots of the same code results, but with the second image being the image created from drawing in the CGLayer. As you can see, it is really jagged, despite being the same code, just drawing into a layerContext. How can I get the lines in the CGLayer to be smooth?
I found the reason the second image is not anti-aliased is because there was nothing to anti-alias against. The background was empty, and so anti-aliasing didn't work. If you make a big rectangle over the bounds of the view that is entirely transparent, the line will draw with anti-aliasing. However, performance is killed. Better not to go this route.
Related
I want to create a little navigation bar on the bottom of my iPhone screen where I basically just draw 5 rectangles next to each other. However, only the active page should have the opacity of 1.0 and others should be slightly transparent (alpha=0.4). That is what I already have.
Now my questions:
How do I change the opacity of the individual elements of my navigation ? Do I have to redraw the whole thing whenever something changes ? So I would have global variables called nav1Opacity,nav2Opacity...nav5Opacity, change them when the navigation changes and redraw the whole thing ? If so,
How do I clear what I have drawn before ? Do i create the rectangles as CGMutablePathRef()s and store them in an array and clear them all ?
I have very little experience with drawing, so I am a little lost there. I have read the documentation of Quartz2d and contexts, but still, as I mentioned I have not fully figured out how it works.
Here is some code I use:
-(void)drawRect:(CGRect)rect{
CGContextRef context = UIGraphicsGetCurrentContext();
//save state
CGContextSaveGState(context);
//NAV1
CGMutablePathRef nav1 = CGPathCreateMutable();
CGPathAddRect(nav1, NULL, CGRectMake(0 , 15, 64, 10));
UIColor *blueColor = UIColorFromRGB(0x35BFE5,0.1);
CGColorRef bC = [blueColor CGColor];
[colorArray addObject:(__bridge id)bC];
[navArray addObject:(__bridge id)nav1];
CGPathRelease(nav1);
/*
*
*
... I do this for all 5 navigation elements
*
*
*/
//then I go through all my rectangles and add/fill them
for(int i=0;i<[navArray count];i++){
CGContextAddPath(context, (__bridge CGMutablePathRef)[navArray objectAtIndex:i]);
CGContextSetFillColorWithColor(context, (__bridge CGColorRef)[colorArray objectAtIndex:i]);
CGContextFillPath(context);
}
// restore to last saved context state
CGContextRestoreGState(context);
}
//and this is how I redraw
-(void)updateActiveNav{
[navArray removeAllObjects];
[colorArray removeAllObjects];
[self setNeedsDisplay];
}
If you actually draw the interface, you will have to redraw it whenever it changes, at least the rectangles that change. You can reuse CGPaths, but they aren't graphical objects on screen, they are just instructions on how to draw shapes, so you will have to draw everything again.
That being said, you can use individual UIViews instead, which represent onscreen objects, and you can change their opacity, which will reflect on screen.
This is the problem:
for(int i=0;i<[navArray count];i++){
CGContextAddPath(context, (__bridge CGMutablePathRef)[navArray objectAtIndex:i]);
CGContextSetFillColorWithColor(context, (__bridge CGColorRef)[colorArray objectAtIndex:i]);
CGContextFillPath(context);
}
You are added the path to your context, then setting a fill color, then filling it. Then without restoring your context you're doing it again so your filling the previous path and the new one. Its not the drawing from the last drawRect its the drawing from here. Try something like below so that after you fill the path you reset the context and draw the next block by itself instead of both the 1st and 2nd etc.
for(int i=0;i<[navArray count];i++){
CGContextSaveGState(context);
// Add Path, Fill
CGContextRestoreGState(context);
}
Background: I have a custom scrollview (subclassed) that has uiimageviews on it that are draggable, based on the drags I need to draw some lines dynamically in a subview of the uiscrollview. (Note I need them in a subview as at a later point i need to change the opacity of the view.)
So before I spend ages developing the code (i'm a newbie so it will take me a while) I looked into what i need to do and found some possible ways. Just wondering what the right way to do this.
Create a subclass of UIView and use the drawRect method to draw the line i need (but unsure how to make it dynamically read in the values)
On the subview use CALayers and draw on there
Create a draw line method using CGContext functions
Something else?
Cheers for the help
Conceptually all your propositions are similar. All of them would lead to the following steps (some of them done invisibly by UIKit):
Setup a bitmap context in memory.
Use Core Graphics to draw the line into the bitmap.
Copy this bitmap to a GPU buffer (a texture).
Compose the layer (view) hierarchy using the GPU.
The expensive part of the above steps are the first three points. They lead to repeated memory allocation, memory copying, and CPU/GPU communication. On the other hand, what you really want to do is lightweight: Draw a line, probably animating start/end points, width, color, alpha, ...
There's an easy way to do this, completely avoiding the described overhead: Use a CALayer for your line, but instead of redrawing the contents on the CPU just fill it completely with the line's color (setting its backgroundColor property to the line's color. Then modify the layer's properties for position, bounds, transform, to make the CALayer cover the exact area of your line.
Of course, this approach can only draw straight lines. But it can also be modified to draw complex visual effects by setting the contents property to an image. You could, for example have fuzzy edges of a glow effect on the line, using this technique.
Though this technique has its limitations, I used it quite often in different apps on the iPhone as well as on the Mac. It always had dramatically superior performance than the core graphics based drawing.
Edit: Code to calculate layer properties:
void setLayerToLineFromAToB(CALayer *layer, CGPoint a, CGPoint b, CGFloat lineWidth)
{
CGPoint center = { 0.5 * (a.x + b.x), 0.5 * (a.y + b.y) };
CGFloat length = sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
CGFloat angle = atan2(a.y - b.y, a.x - b.x);
layer.position = center;
layer.bounds = (CGRect) { {0, 0}, { length + lineWidth, lineWidth } };
layer.transform = CATransform3DMakeRotation(angle, 0, 0, 1);
}
2nd Edit: Here's a simple test project which shows the dramatical difference in performance between Core Graphics and Core Animation based rendering.
3rd Edit: The results are quite impressive: Rendering 30 draggable views, each connected to each other (resulting in 435 lines) renders smoothly at 60Hz on an iPad 2 using Core Animation. When using the classic approach, the framerate drops to 5 Hz and memory warnings eventually appear.
First, for drawing on iOS you need a context and when drawing on the screen you cannot get the context outside of drawRect: (UIView) or drawLayer:inContext: (CALayer). This means option 3 is out (if you meant to do it outside a drawRect: method).
You could go for a CALayer, but I'd go for a UIView here. As far as I have understood your setup, you have this:
UIScrollView
| | |
ViewA ViewB LineView
So LineView is a sibling of ViewA and ViewB, would need be big enough to cover both ViewA and ViewB and is arranged to be in front of both (and has setOpaque:NO set).
The implementation of LineView would be pretty straight forward: give it two properties point1 and point2 of type CGPoint. Optionally, implement the setPoint1:/setPoint2: methods yourself so it always calls [self setNeedsDisplay]; so it redraws itself once a point has been changed.
In LineView's drawRect:, all you need to is draw the line either with CoreGraphics or with UIBezierPath. Which one to use is more or less a matter of taste. When you like to use CoreGraphics, you do it like this:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
// Set up color, line width, etc. first.
CGContextMoveToPoint(context, point1);
CGContextAddLineToPoint(context, point2);
CGContextStrokePath(context);
}
Using NSBezierPath, it'd look quite similar:
- (void)drawRect:(CGRect)rect
{
UIBezierPath *path = [UIBezierPath bezierPath];
// Set up color, line width, etc. first.
[path moveToPoint:point1];
[path addLineToPoint:point2];
[path stroke];
}
The magic is now getting the correct coordinates for point1 and point2. I assume you have a controller that can see all the views. UIView has two nice utility methods, convertPoint:toView: and convertPoint:fromView: that you'll need here. Here's dummy code for the controller that would cause the LineView to draw a line between the centers of ViewA and ViewB:
- (void)connectTheViews
{
CGPoint p1, p2;
CGRect frame;
frame = [viewA frame];
p1 = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame));
frame = [viewB frame];
p2 = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame));
// Convert them to coordinate system of the scrollview
p1 = [scrollView convertPoint:p1 fromView:viewA];
p2 = [scrollView convertPoint:p2 fromView:viewB];
// And now into coordinate system of target view.
p1 = [scrollView convertPoint:p1 toView:lineView];
p2 = [scrollView convertPoint:p2 toView:lineView];
// Set the points.
[lineView setPoint1:p1];
[lineView setPoint2:p2];
[lineView setNeedsDisplay]; // If the properties don't set it already
}
Since I don't know how you've implemented the dragging I can't tell you how to trigger calling this method on the controller. If it's done entirely encapsulated in your views and the controller is not involved, I'd go for a NSNotification that you post every time the view is dragged to a new coordinate. The controller would listen for the notification and call the aforementioned method to update the LineView.
One last note: you might want to call setUserInteractionEnabled:NO on your LineView in its initWithFrame: method so that a touch on the line will go through to the view under the line.
Happy coding !
I'v got this piece of code :
CGColorSpaceRef rgb = CGColorSpaceCreateDeviceRGB();
CGFloat colors[] = {
1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f,
};
CGGradientRef gradientRef = CGGradientCreateWithColorComponents(rgb, colors, NULL, sizeof(colors) / (sizeof(colors[0]) * 4));
CGColorSpaceRelease(rgb);
CGContextRef context = UIGraphicsGetCurrentContext();
CGRect rect = theCell.backgroundView.bounds;
CGPoint start = CGPointMake(rect.origin.x, 0);
CGPoint end = CGPointMake(rect.origin.x, rect.size.height/2);
CGContextDrawLinearGradient(context, gradientRef, start, end, kCGGradientDrawsBeforeStartLocation | kCGGradientDrawsAfterEndLocation);
And I wonder how I can make it draw into a designated view and a clipping rect passed in parameters to my function. Tip: I don't mind about drawRect, I'm not subclassing anything.
Tip 2: I don't want to insert any layers that I won't be able to remove later.
Tip 3: This piece of code does not draw anything that my eyes could see..... :-( Missing a graphic port ?
Tip 4: I'd like to erase the draw simply changing the background color, and it's done...
CGContextRef context = UIGraphicsGetCurrentContext(); will get the graphics context for the current view, so if you call this in the drawRect: method of a UIView it will draw.
I don't understand what you mean by:
I don't mind about drawRect, I'm not
subclassing anything
but if you want to do custom drawing you must either override the drawRect: method or use layers. To use layers you would call CGContextRef context = CGLayerGetContext(theLayer); instead of CGContextRef context = UIGraphicsGetCurrentContext();.
Ok, so I looked at the documentation and it says that you can get a CGContextRef by calling UIGraphicsGetCurrentContext() from the drawRectMethod. Here's what it says: In an iOS application, you set up a UIView object to draw to and implement the drawRect: method to perform drawing. Before calling your custom drawRect: method, the view object automatically configures its drawing environment so that your code can start drawing immediately. As part of this configuration, the UIView object creates a graphics context (a CGContextRef opaque type) for the current drawing environment. You obtain this graphics context by calling the UIKit function UIGraphicsGetCurrentContext. You save and restore graphics contexts using the functions UIGraphicsPushContext and UIGraphicsPopContext.
You can create custom graphics context objects in situations where you want to draw somewhere other than your view. For example, you may want to capture a series of drawing commands and use them to create an image or a PDF file. To create the context, you use the CGBitmapContextCreate or CGPDFContextCreate function. After you have the context, you can pass it to the drawing functions needed to create your content.
When creating custom contexts, the coordinate system for those contexts is different from the native coordinate system used by iOS. Instead of the origin being in the upper-left corner of the drawing surface, it is in the lower-left corner and the axes point up and to the right. The coordinates you specify in your drawing commands must take this into consideration or the resulting image or PDF file may appear wrong when rendered. See “Creating a Bitmap Graphics Context” and “Creating a PDF Graphics Context” for details on using CGBitmapContextCreate and CGPDFContextCreate.
Might I recommend you look into the CAGradientLayer, and add it as a sublayer of your view? Lots simpler, and it will be hardware accelerated which matters for table cells.
Example stolen partly from here:
http://tumbljack.com/post/188089679/gpu-accelerated-awesomeness-with-cagradientlayer
#import <QuartzCore/QuartzCore.h> // Also import this framework
......
CAGradientLayer grad = [CAGradientLayer layer];
UIColor *colorOne = [UIColor colorWithHRed:1.0f Green:1.0f Blue:1.0f alpha:1.0f];
UIColor *colorTwo = [UIColor colorWithHRed:0.0f Green:0.0f Blue:0.0f alpha:1.0f];
NSArray *colors = [NSArray arrayWithObjects:(id)colorOne.CGColor, colorTwo.CGColor, nil];
grad.colors = colors;
CGRect rect = theCell.backgroundView.bounds;
rect.size.height = rect.size.height / 2;
grad.frame = rect;
[self.layer addsublayer:grad]
You may have to play with the colors a bit, not sure if you had the gradient tilted or not...
Our main UIView is a UIScrollView with a fixed background image (very common, obviously). In that scrollView, we have several UIViews that hold content and scroll up and down as the user scrolls (also common). Those UIViews each have their own background, a simple gradient from white to black.
The goal is to have the background gradient of those (inner) UIViews be partially opaque AND use a CGBlendMode other than "kCGBlendModeNormal" (specifically, "kCGBlendModeOverlay"). You should be able to see through to the "parent" scrollView’s fixed background image as the UIViews scroll up and down above it.
- (void)drawRect:(CGRect)rect {
gradientStart = [UIColor colorWithRed:1 green:1 blue:1 alpha:1.0];
gradientEnd = [UIColor colorWithRed:0 green:0 blue:0 alpha:1.0];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[2] = { 0.0f, 1.0f };
NSArray *colors = [NSArray arrayWithObjects:(id)gradientStart.CGColor, (id)gradientEnd.CGColor, nil];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (CFArrayRef)colors, locations);
CGColorSpaceRelease(colorSpace);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetAlpha(context, 0.50); //this works!
CGContextSetBlendMode(context, kCGBlendModeOverlay); //doesn’t seem to do anything!
CGContextClearRect(context, rect);
CGPoint startPoint, endPoint;
startPoint.x = 0.0;
startPoint.y = 0.0;
endPoint.x = 0.0;
endPoint.y = rect.size.height;
CGContextDrawLinearGradient(context, gradient, startPoint, endPoint, 0);
CGGradientRelease(gradient);
[super drawRect:rect];
}
Everything works as expected except the CGContextSetBlendMode, which is ignored. We can't seem to find a way to change the blendMode of a UIView relative to what is behind it, the same way you can with alpha. Please note that this is different than building up multiple layers in a SINGLE UIView; in that case, this technique does change the blendMode of the layers "on top". We want to see through to the parent scrollView's fixed background image (as we scroll the child view up and down above it), with both an alpha and an overlay blend applied.
Here's an image showing the issue: http://img2.sbck.us/blendmode.png
Thanks in advance for your help!
I believe what you want is not possible with your current setup. On iOS, it is simply not possible for the blend mode of a view to have an effect on the stuff that is drawn under the view. You would have to draw the scroll view's background and the gradients in the same view.
This is possible, at least with two image views. It might even be possible with more general views. The approach is to implement drawRect in the parent view, and do as follows:
Determine the rect for the foreground view.
Convert the rect in the foreground view to a rect in the background view.
Begin a new graphics context.
Draw the background with the proper blend mode.
Draw the foreground with the proper blend mode.
Extract the image from the graphics context.
End the graphics context.
Use the extracted image accordingly.
This allows a foreground image to blend with a background image.
Seems like you could do this by setting the 'compositingFilter' property of your view's CALayer. The comment in CALayer.h says "A filter object used to composite the layer with its (possibly filtered) background. Default value is nil, which implies source-over compositing."
Alas, CoreImage which provides the filters is not (officially) available on iOS.
I guess your other alternative would be to use OpenGL. You could still use UIView with OpenGL after a fashion by rendering your UIView's into images which could then be used a textures.
I've recently asked a question about clipping an image via path at view's drawRect method.
iPhone clip image with path
Krasnyk's code is copied below.
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGMutablePathRef path = CGPathCreateMutable();
//or for e.g. CGPathAddRect(path, NULL, CGRectInset([self bounds], 10, 20));
CGPathAddEllipseInRect(path, NULL, [self bounds]);
CGContextAddPath(context, path);
CGContextClip(context);
CGPathRelease(path);
[[UIImage imageNamed:#"GC.png"] drawInRect:[self bounds]];
}
It works very well. However, when my image is larger than the view itself, how do I show different parts of the image?
I tried tweaking around with translation on the locations (show as bounds above) of ellipse and/or UIImage drawInRect but some complex effects (Unwanted clipping, weird elipse size) I can't explain happens.
EDIT: Maybe I can answer my own question. I can try drawAtPoint instead of drawInRect? Or drawInRect and set the origin to a different location, but expand the size of the rectangle at the same time?
Does that incur performance penalty when I am drawing a larger rectangle than is showing through the view?
Sounds like you've about figured it out for yourself. drawAtPoint is what you should use. drawInRect will scale the image to fit the destination rect, which is computationally more expensive. Assuming your image is larger than your view, you'll be passing negative x and y values to drawAtPoint in order to clip interior portions of the image.
The example below should display the center portion your image, within your view:
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddEllipseInRect(path, NULL, [self bounds]);
CGContextAddPath(context, path);
CGContextClip(context);
CGPathRelease(path);
UIImage *bigImage = [UIImage imageNamed:#"GC.png"];
CGPoint topLeftOffset = CGPointMake((self.bounds.size.width - bigImage.size.width) / 2,(self.bounds.size.height - bigImage.size.height) / 2);
[bigImage drawAtPoint: topLeftOffset];
}