MKMapView - Redrawing overlays in the most efficient way - iphone

I have an MKMapView with 2 overlays. They represent 1. The route someone has taken. 2. A series of circular regions of interest. In order to update either of the overlays I update their data, then invalidate their related view:
[(RoutePolyline *)self.overlay appendPolylines:polylines];
MKOverlayPathView *overlayView = (MKOverlayPathView *)[self.mapView viewForOverlay:self.overlay];
[overlayView invalidatePath];
The problem is that adding a single line to my RoutePolyline and invalidating its related view causes every overlay view to be redrawn about 80 times. Given that this happens for every location update this is incredibly expensive.
Here is the code from the only method in my RouteOverlayView:
- (void)drawMapRect:(MKMapRect)mapRect
zoomScale:(MKZoomScale)zoomScale
inContext:(CGContextRef)context
{
RoutePolyline *routePolyline = (RoutePolyline *)self.overlay;
int polylineCount = [routePolyline.polylines count];
for (int i = 0; i < polylineCount; i++)
{
MKPolyline *polyline = [routePolyline.polylines objectAtIndex:i];
CGPathRef path = [MKUtils newPolyPathWithPolyline:polyline overlayView:self];
if (path)
{
[self applyFillPropertiesToContext:context atZoomScale:zoomScale];
CGContextBeginPath(context);
CGContextAddPath(context, path);
CGContextDrawPath(context, kCGPathStroke);
[self applyStrokePropertiesToContext:context atZoomScale:zoomScale];
CGContextBeginPath(context);
CGContextAddPath(context, path);
CGContextStrokePath(context);
CGPathRelease(path);
}
}
}
What could be causing these extra redraws?

Related

Draw lines with centers without them overlap

I have a problem when i try to join lines. Here is a picture:
and I like that it looks like this:
and my code is:
- (void) drawRect:(CGRect)rect {
[super drawRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
const CGFloat *components = CGColorGetComponents(self.lineColor.CGColor);
CGFloat red;
CGFloat green;
CGFloat blue;
CGFloat alpha;
if(CGColorGetNumberOfComponents(self.lineColor.CGColor) == 2)
{
red = 1;
green = 1;
blue = 1;
alpha = 1;
}
else
{
red = components[0];
green = components[1];
blue = components[2];
alpha = components[3];
if (alpha <= 0) alpha = 1;
}
// set the stroke color and width
CGContextSetRGBStrokeColor(context, red, green, blue, alpha);
CGContextSetLineWidth(context, 2.0);
if (self.points.count >0) {
BezierPoint *firstPoint = [self.points objectAtIndex:0];
CGContextMoveToPoint(context, firstPoint.center.x, firstPoint.center.y);
int index = 0;
for (BezierPoint *point in self.points ) {
if(index == 0){
index++;
continue;
}
CGContextAddLineToPoint(context, point.center.x, point.center.y);
}
CGContextAddLineToPoint(context, firstPoint.center.x, firstPoint.center.y);
}
CGContextSetRGBFillColor(context, 0.0, 0.0, 0.0, 0.0);
CGContextDrawPath(context, kCGPathFillStroke);
}
the problem I have is that for every point you add, the lines overlap and I would like that as I stay I add points for geometric figure that globulins do not overlap
If anyone can help me I will thank!!
I would move the logic that determines the order the lines are drawn to your view controller, and access the data needed to draw the view with from a delegate using a protocol. Views should not own their data. For example, in your .h try something like;
#import <UIKit/UIKit.h>
#protocol CowDrawViewDataSource
-(NSArray *) pointsToDraw;
#end
#interface CowDrawView : UIView
#property (nonatomic , weak) id <CowDrawViewDataSource> dataSource;
#end
Then, (and I hope this does answer you question) in the view controller, you set as your views delegate, construct the
-(NSArray *) pointsToDraw;
method, in such a way, to send your array of points in an order in from which they can be drawn. Say by finding the point the top/left point, then the top/right, then bottom/right, bottom/left. (although such an approach might not work so well with irregular polygons, and shapes that are contiguous, but not polygons.)
After you figure out how to get the array in the order you want, you can get it in your drawRect by sending a message to it's delegate such as
NSArray *points = [self.dataSource pointToDraw];
with little re-work in the drawRect it's self.
The easy way to correct your problem is first draw only single line segments between two points and see the results. Then you can form loops. I guess you are not assigning perfect coordinates points or your loop must consist of :
CGContextAddLineToPoint(context, point.center.x, point.center.y);
And then,
CGContextMoveToPoint(context, point.center.x, point.center.y);
This shows that first draw line and move to next point.
Hope this helps.

Transparency/Alpha and MKOverlayView issue

Having wrestled with many problems with MKOverlayViews and MKMapKit I find myself with one more. I'm using an MKOverlayPathView subclass to draw a singular large overlay on the screen (it covers London at the moment). Within that overlay are lots of coloured squares for arguments sake:
- (void)drawMapRect:(MKMapRect)mapRect
zoomScale:(MKZoomScale)zoomScale
inContext:(CGContextRef)context
{
int size = 0;
min = 0;
max = 0;
CGFloat alpha = 0.4f;
int recursionLevel = 4;
QuadNodeOverlay *quadNodeOverlay = (QuadNodeOverlay *)self.overlay;
Cluster *clusters = quadtree_clusters(quadNodeOverlay.quadTree, recursionLevel, &size);
if (clusteringMethod == 1) {
/* Draw paths/squares */
CGPathRef *paths = [self createPaths:clusters size:size];
for (int i = 0; i < size; i++) {
CGPathRef path = paths[i];
Cluster cluster = clusters[i];
CGContextBeginPath(context);
CGContextAddPath(context, path);
//CGContextSetFillColorWithColor(context, colors[cluster.depth]);
CGColorRef gradientColor = [self newColor:cluster.count];
CGContextSetFillColorWithColor(context, gradientColor);
CGContextDrawPath(context, kCGPathFillStroke);
CGColorRelease(gradientColor);
CGPathRelease(path);
}
free(paths);
} else if (clusteringMethod == 2) {
// CUT
}
[self setAlpha:alpha];
}
The above code is incomplete but provides a solid basis for the question. The code works fine and performs admirable fast regardless of the number of squares I want to draw. The problem I have is below a certain point I'm not drawing this overlay; I manage this in the view controller containing the map:
- (void)mapView:(MKMapView *)map regionDidChangeAnimated:(BOOL)animated {
self.annotations = [locationServer itemsForMapRegion:map.region withMapView:map maxCount:100];
NSLog(#"There are like %d cards dude.",[self.annotations count]);
if ( [self.annotations count] > 40) {
[mapView removeAnnotations:annotations];
// Cluster
if (![[mapView overlays] containsObject:quadClusters]) {
[mapView addOverlay:quadClusters];
}
} else {
// Don't
[mapView removeOverlay:quadClusters];
// Add pins.
[mapView removeAnnotations:annotations];
[mapView addAnnotations:annotations];
}
}
Again this code works fine my purposes right now. The problem is when I zoom in to a level where the clusters are not displayed but the individual annotations are when I zoom back out a chuck of the overlay is rendered without transparency. Vis:
As a foot note. Removing the setAlpha from the overlay and modifying the code that draws the squares to read:
CGColorRef gradientColor = [self newColor:cluster.count];
CGColorRef alphaGradientColor = CGColorCreateCopyWithAlpha(gradientColor, alpha);
CGContextSetFillColorWithColor(context, alphaGradientColor);
resolves the issue, however surely applying the alpha channel to the overlay as a whole is more efficient.

How to implement undo in a drawing app

Below is the code snippet of painting. I can do undo in a vector drawing just like storing points and remove the highest one from mutable array then redrawing.However, it does not function properly in a raster drawing.
If I use UIGraphicsGetCurrentContext() as a context reference, undo works well. But the context of CGBitmapContextCreate() does not when issue undo action.
- (id)initWithFrame:(CGRect)frame {
objArray = [[NSMutableArray alloc] init];
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
canvas = CGBitmapContextCreate(NULL, drawImage.frame.size.width, drawImage.frame.size.height, 8, 0, colorSpace, kCGImageAlphaPremultipliedLast);
CGColorSpaceRelease(colorSpace);
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGImageRef imgRef = CGBitmapContextCreateImage(canvas);
CGRect r = self.bounds;
CGContextDrawImage(context, CGRectMake(0, 0, r.size.width, r.size.height), imgRef);
if(ok) {
for (int i = 0; i < [objArray count]; i++) {
CGPoint point = [[[objArray objectAtIndex: i] objectAtIndex:0] CGPointValue];
CGContextMoveToPoint(canvas, point.x, point.y);
for (int j = 0; j < [[objArray objectAtIndex:i] count]; j++) {
point = [[[objArray objectAtIndex: i] objectAtIndex:j] CGPointValue];
CGContextAddLineToPoint(canvas, point.x, point.y);
CGContextStrokePath(**canvas**);
CGContextMoveToPoint(**canvas**, point.x, point.y);
}
}
}
CGImageRelease(imgRef);
}
- (void)undo:(id) sender {
NSLog(#"click");
if([objArray count] > 0)
[objArray removeLastObject];
ok = YES;
[self setNeedsDisplay];
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
NSMutableArray *points = [NSMutableArray array];
UITouch *touch = nil;
if (touchPoint) {
touch = [touches member:touchPoint];
}
end = [touch locationInView:self];
[points addObject:[NSValue valueWithCGPoint:start]];
[points addObject:[NSValue valueWithCGPoint:end]];
[objArray addObject:points];
CGContextMoveToPoint(**canvas**, start.x, start.y);
CGContextAddLineToPoint(**canvas**, end.x, end.y);
CGContextSetLineCap(**canvas**, kCGLineCapRound);
CGContextSetLineWidth(**canvas**, 40.0);
CGContextStrokePath(**canvas**);
start = end;
[self setNeedsDisplay];
}
With raster drawing you're changing the pixels in the canvas each time, there are no objects like there are in a vector drawing.
As a result the only "state" you have is the canvas itself. In order to allow for undo you actually need to save a copy of the canvas before each change. Right before you make the change you'll copy the old bitmap context and then make the change. If the user chooses to undo then you'll just copy the saved context over the normal one. If you want to allow for multiple undos you'll have to save multiple copies.
Obviously this can become memory intensive. Technically you don't actually have to save the whole canvas, just the part that has changes on it, with a record of the position of the changed section. If changes are small then you'll save quite a bit of memory, but some changes can affect the whole canvas, not saving anything.
You could potentially save even more memory with algorithms that store changed pixels, but the processing overhead isn't likely worth it.
Assumming you're storing the image in an Image object, create a stack:
Stack undoStack = ...
Stack redoStack = ...
The high memory solution
As the user makes changes you to the image, you can store the next image (w the changes), and the next and the next and so on. When the user wants to undo, you restore the images by popping from the undoStack and pushing onto the redo stack:
void undo(){
redoStack.push(undoStack.pop());
}
To redo, use the same process, but backwards.
The low memory solution
The concent is the same as above, but now instead of storing the whole image, you can XOR the modified image with the previous one (or with the original one) and store only the pixels that have changed and coordinates at which these changes occur. You might even consider quad tree packing of this new XORed image to save memory if the changes are not great.

Huge Memory Leak in CGMutablePathRef

I Have Rendered nearly 1000 Polygons in the map. I get the path of the polygon using
- (CGPathRef)polyPath:(MKPolygon *)polygon
{
MKMapPoint *points = [polygon points];
NSUInteger pointCount = [polygon pointCount];
NSUInteger i;
if (pointCount < 3)
return NULL;
CGMutablePathRef path = CGPathCreateMutable();
if([polygon isKindOfClass:[MKPolygon class]])
{
for (MKPolygon *interiorPolygon in polygon.interiorPolygons)
{
CGPathRef interiorPath = [self polyPath:interiorPolygon];
CGPathAddPath(path, NULL, interiorPath);
CGPathRelease(interiorPath);
}
}
CGPoint relativePoint = [self pointForMapPoint:points[0]];
CGPathMoveToPoint(path, NULL, relativePoint.x, relativePoint.y);
for (i = 1; i < pointCount; i++)
{
relativePoint = [self pointForMapPoint:points[i]];
CGPathAddLineToPoint(path, NULL, relativePoint.x, relativePoint.y);
}
return path;
}
- (void)drawMapRect:(MKMapRect)mapRect
zoomScale:(MKZoomScale)zoomScale
inContext:(CGContextRef)context
{
MultiPolygon *multiPolygon = (MultiPolygon *)self.overlay;
for (MKPolygon *polygon in multiPolygon.polygons)
{
if([polygon isKindOfClass:[MKPolygon class]])
{
CGPathRef path = [self polyPath:polygon];
if (path)
{
[self applyFillPropertiesToContext:context atZoomScale:zoomScale];
CGContextBeginPath(context);
CGContextAddPath(context, path);
CGContextDrawPath(context, kCGPathEOFill);
[self applyStrokePropertiesToContext:context atZoomScale:zoomScale];
CGContextBeginPath(context);
CGContextAddPath(context, path);
CGContextSetAlpha(context,1.0);
CGContextStrokePath(context);
}
CGPathRelease(path);
}
}
}
I get leak in
CGPathRelease(interiorPath);
and
return path;
I know that i have to release path using CGPathRelease but where to release it while i have to return.
Both leaks a huge memory.
I have been working on this for days, Please help.
Thanks in Advance
You should rename your method to be -createPolyPath: to make it clear that it is returning a Core Foundation object that needs to be released, then in the code in which you call -createPolyPath:, you need to release it like so:
CGPathRef path = [someObjectOrClass createPolyPath:somePolygon];
// Do some stuff with the path
CGPathRelease(path);
See the "Memory Management Programming Guide for Core Foundation":
I think that you must rename your method starting with new like newPolyPath.... I'll done that and it's work now for me with no more leaks on path...
You also must use CGPathRelease(path); after each use of your path.
Try using CGPathRelease(path);
For example:
CGMutablePathRef path = CGPathCreateMutable(); // created memory allocation
CGPathCloseSubpath(path);
CGPathRelease(path); // released path allocation
Great tip found here:
http://the.ichibod.com/kiji/ios-memory-management-tips/

iPhone: drawRect called once

I'm calling setNeedsDisplayInRect from an NSTimer function every two seconds. This works perfectly, and draws a square in a random position, with a random color. However, in some circumstances I would like to draw a square x number of times in the NSTimer function (using a for loop) - but, after numerous error testing it seems that drawRect is only called once even though I am running setNeedsDisplayInRect x number of times? I would love some help as I've been trying to figure out this problem all day long. Carl.
Edit below is my code...
View
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(context, 2.0);
CGContextSetStrokeColorWithColor(context, currentColor.CGColor);
CGContextSetFillColorWithColor(context, currentColor.CGColor);
CGContextAddRect(context, redrawRect);
CGContextDrawPath(context, kCGPathFillStroke);
}
-(void)drawInitializer
{
int x = (int)arc4random() % [self.xCoordinates count];
int y = (int)arc4random() % [self.yCoordinates count];
self.currentColor = [UIColor randomColor];
self.redrawRect = CGRectMake ([[self.xCoordinates objectAtIndex:x] intValue], [[self.yCoordinates objectAtIndex:y] intValue], 25, 25);
[self setNeedsDisplayInRect:redrawRect];
}
Controller
- (void) handleTimer: (NSTimer *) timer
{
for(int i=0; i<5; i++)
{
[self.squareView drawInitializer];
}
}
You could refactor the code so that you have a simple class that:
stores color
stores position
has a method to generate random positions, colors, ...
You could then create as many instances as you want and push them into a NSMutableArray.
This way you can iterate over that list, and draw each object in your draw routine.
Whenever you add/delete/modify one of your objects, call setNeedsDisplay:
you could create a class that has the ability to draw itself, then create as many instances of this class that you need.