I am using mapkit on iPhone with iOS 4.
I am using a custom overlay and a custom overlay view, to draw shapes on the map.
At the moment, shapes are just rectangles, but I am planning something more sophisticated. This is why I am not using the MKPolygon overlay type.
This is the code for my overlay view drawing method:
-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
// Clip context to bounding rectangle
MKMapRect boundingMapRect = [[self overlay] boundingMapRect];
CGRect boundingRect = [self rectForMapRect:boundingMapRect];
CGContextAddRect(context, boundingRect);
CGContextClip(context);
// Define shape
CGRect shapeRect = CGRectMake(0.5f, 0.5f, boundingRect.size.width - 1.0f, boundingRect.size.height - 1.0f);
// Fill
CGContextSetRGBFillColor(context, 0.5f, 0.5f, 0.5f, 0.5f);
CGContextFillRect(context, shapeRect);
// Stroke
CGContextSetRGBStrokeColor(context, 0, 0, 0, 0.75f);
CGContextSetLineWidth(context, 1.0f);
CGContextStrokeRect(context, shapeRect);
}
The problem is that rectangles get correctly filled (so it appears their bounding rect is correctly set), but they don't get stroked.
Can anyone help?
Thanks!
As reported in some previous comments, the problem is with line width. More generally, all drawing is automatically scaled to follow the map zooming, so if you want some of your drawing metrics to be zoom-independent, you have to divide it by zoomScale.
Here is the new code, that works correctly on my iPhone 4:
-(void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
{
// Clip context to bounding rectangle
MKMapRect boundingMapRect = [[self overlay] boundingMapRect];
CGRect boundingRect = [self rectForMapRect:boundingMapRect];
CGContextAddRect(context, boundingRect);
CGContextClip(context);
// Define shape
CGRect shapeRect = CGRectInset(boundingRect, 2.0f / zoomScale, 2.0f / zoomScale);
// Fill
CGContextSetRGBFillColor(context, 0.5f, 0.5f, 0.5f, 0.5f);
CGContextFillRect(context, shapeRect);
// Stroke
CGContextSetRGBStrokeColor(context, 0, 0, 0, 0.75f);
CGContextSetLineWidth(context, 4.0f / zoomScale);
CGContextStrokeRect(context, shapeRect);
}
I will also report the code I am using in the overlay to calculate and return the bounding rectangle, because I think it can help:
-(MKMapRect)boundingMapRect
{
// Overlay bounds
CLLocationCoordinate2D topLeftcoordinate = <the top-left coordinate of overlay>;
CLLocationCoordinate2D bottomRightCoordinate = <the bottom-right coordinate of overlay>;
// Convert them to map points
MKMapPoint topLeftPoint = MKMapPointForCoordinate(topLeftcoordinate);
MKMapPoint bottomRightPoint = MKMapPointForCoordinate(bottomRightCoordinate);
// Calculate map rect
return MKMapRectMake(topLeftPoint.x, topLeftPoint.y, bottomRightPoint.x - topLeftPoint.x, topLeftPoint.y - bottomRightPoint.y);
}
Thank you all for your comments and suggestions.
Currently, we should use MKOverlayRenderer instead of MKOverlayView.
In method -(void)drawMapRect:(MKMapRect)mapRect
zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context,
use scaleFactor for configuring the stroke width of lines or other
attributes that might be affected by the scale of the map’s
contents.
Refer to Apple official site drawMapRect:zoomScale:inContext: of MKOverlayRenderer.
Related
I need a radial gradient in the shape of an oval or ellipse and it seems like it CGContextDrawRadialGradient can only draw a perfect circle. I've been drawing to a square context then copying/drawing into a rectangular context.
Any better way to do this?
Thanks!
The only way I've found to do this is as Mark F suggested, but I think the answer needs an example to be easier to understand.
Draw an elliptical gradient in a view in iOS (and using ARC):
- (void)drawRect:(CGRect)rect {
CGContextRef ctx = UIGraphicsGetCurrentContext();
// Create gradient
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGFloat locations[] = {0.0, 1.0};
UIColor *centerColor = [UIColor orangeColor];
UIColor *edgeColor = [UIColor purpleColor];
NSArray *colors = [NSArray arrayWithObjects:(__bridge id)centerColor.CGColor, (__bridge id)edgeColor.CGColor, nil];
CGGradientRef gradient = CGGradientCreateWithColors(colorSpace, (__bridge CFArrayRef)colors, locations);
// Scaling transformation and keeping track of the inverse
CGAffineTransform scaleT = CGAffineTransformMakeScale(2, 1.0);
CGAffineTransform invScaleT = CGAffineTransformInvert(scaleT);
// Extract the Sx and Sy elements from the inverse matrix
// (See the Quartz documentation for the math behind the matrices)
CGPoint invS = CGPointMake(invScaleT.a, invScaleT.d);
// Transform center and radius of gradient with the inverse
CGPoint center = CGPointMake((self.bounds.size.width / 2) * invS.x, (self.bounds.size.height / 2) * invS.y);
CGFloat radius = (self.bounds.size.width / 2) * invS.x;
// Draw the gradient with the scale transform on the context
CGContextScaleCTM(ctx, scaleT.a, scaleT.d);
CGContextDrawRadialGradient(ctx, gradient, center, 0, center, radius, kCGGradientDrawsBeforeStartLocation);
// Reset the context
CGContextScaleCTM(ctx, invS.x, invS.y);
// Continue to draw whatever else ...
// Clean up the memory used by Quartz
CGGradientRelease(gradient);
CGColorSpaceRelease(colorSpace);
}
Put in a view with a black background you get:
You can change the transform of the context to draw an ellipse (for example, apply CGContextScaleCTM(context, 2.0, 1.0) just before calling CGContextDrawRadialGradient () to draw an elliptical gradient that's twice as wide as it is high). Just remember to apply the inverse transform to your start and end points, though.
I want to accomplish a function just like a Brush. The area where finger swipes changes to trasparent with gradually changed border.
I can only change the color to crystal clear now with following codes:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
if(self.eraser) return;
CGFloat scale = self.transform.a;
if (scale < 1) scale = 1;
CGPoint p = [[touches anyObject] locationInView: self];
CGPoint q = [[touches anyObject] previousLocationInView: self];
UIImage* image;
image = self.image;
CGSize size = self.frame.size;
UIGraphicsBeginImageContext(size);
CGRect rect;
rect.origin = CGPointZero;
rect.size = size;
[image drawInRect:rect];
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetLineCap(context, kCGLineCapRound);
CGContextBeginPath(context);
CGContextSaveGState( context );
CGContextSetLineWidth(context, (10.0 / scale) + 1);
CGContextSetBlendMode(context, kCGBlendModeClear);
CGContextMoveToPoint(context, q.x, q.y);
CGContextAddLineToPoint(context, p.x, p.y);
CGContextStrokePath(context);
CGContextRestoreGState( context );
UIImage* editedImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
[self setBounds:rect];
[self setImage:editedImage];
}
How can I get the edge with gradually change? Thanks in advance.
You can achieve this effect by drawing a radial gradient with a variable alpha in the kCGBlendModeDestinationIn mode in each spot the user passes.
This blend mode has the effect of only applying the layer's alpha to layers below. With the variable alpha of our gradient, we can achieve this effect.
const CGFloat kBrushSize = 10.f;
CGContextSaveGState(context);
// Make a radial gradient that goes from transparent black on the inside
// to opaque back on the outside.
size_t num_locations = 2;
CGFloat locations[2] = { 0.0, 1.0 };
CGFloat components[8] = { 1.0, 1.0, 1.0, 0.0,
1.0, 1.0, 1.0, 1.0 };
CGColorSpaceRef myColorspace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);
CGGradientRef myGradient = CGGradientCreateWithColorComponents (myColorspace, components,
locations, num_locations);
CGColorSpaceRelease(myColorspace);
// Draw the gradient at the point using kCGBlendModeDestinationIn
// This mode only applies the new layer's alpha to the lower layer.
CGContextSetBlendMode(context, kCGBlendModeDestinationIn);
CGContextDrawRadialGradient(context, myGradient, p, 0.f, p, (kBrushSize / scale) + 1, kCGGradientDrawsAfterEndLocation);
CGGradientRelease(myGradient);
CGContextRestoreGState(context);
Here is a screenshot of this code in action:
Note: Using this technique, if the user is moving his/her finger very fast, you may see a spacing effect where discrete brush dots are visible. This is a feature of some graphics software, but if this is undesirable for you, you can add code to interpolate the points between the current and last to draw more brush points, creating a more continuous stroke.
Also, you should be able to adjust the gradient color stops to achieve any kind of brush softness you like.
Source: https://developer.apple.com/library/mac/documentation/GraphicsImaging/Conceptual/drawingwithquartz2d/dq_shadings/dq_shadings.html
I'm using a MKCircleRenderer which is going to be repainted when the size of the circle is changed, but when the circle resizes, this happens...
Screenshot
Instead of a circle, it ends drawing a square when it doesn't have space
this is the method I'm using
- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)ctx{
MKMapPoint mpoint = MKMapPointForCoordinate([[self overlay] coordinate]);
CGFloat radiusAtLatitude = (_mapRadius)*MKMapPointsPerMeterAtLatitude([[self overlay] coordinate].latitude);
MKMapRect circleRect = MKMapRectMake(mpoint.x, mpoint.y, radiusAtLatitude,radiusAtLatitude);
CGRect overlayRect = [self rectForMapRect:circleRect];
UIGraphicsPushContext(ctx);
CGContextSetStrokeColorWithColor(ctx, self.fillColor.CGColor);
CGContextSetFillColorWithColor(ctx, [self.fillColor colorWithAlphaComponent:_circleAlpha].CGColor);
CGContextSetLineWidth(ctx, _border);
CGContextSetShouldAntialias(ctx, YES);
CGContextAddArc(ctx, overlayRect.origin.x, overlayRect.origin.y, radiusAtLatitude, 0, 2 * M_PI, true);
CGContextDrawPath(ctx, kCGPathFillStroke);
UIGraphicsPopContext();
}
Any clue would help me a lot, thanks in advance!
i have just a problem with my MKPolyLineView. I simply try to make a color gradient to the Polyline, but with CAGradient it doenst work. I subclasses MKPolylineView and redrawing in
- (void)drawMapRect:(MKMapRect)mapRect zoomScale:(MKZoomScale)zoomScale inContext:(CGContextRef)context
UIColor *darker = [UIColor blackColor];
CGFloat baseWidth = self.lineWidth / zoomScale;
// draw the dark colour thicker
CGContextAddPath(context, self.path);
CGContextSetStrokeColorWithColor(context, darker.CGColor);
CGContextSetLineWidth(context, baseWidth * 1.5);
CGContextSetLineCap(context, self.lineCap);
CGContextStrokePath(context);
// now draw the stroke color with the regular width
CGContextAddPath(context, self.path);
CGContextSetStrokeColorWithColor(context, self.strokeColor.CGColor);
CGContextSetLineWidth(context, baseWidth);
CGContextSetLineCap(context, self.lineCap);
CGContextStrokePath(context);
[super drawMapRect:mapRect zoomScale:zoomScale inContext:context];
}
but even that is not working (StrokeColor = red). Any ideas how to get a gradient into
the Polyline? (Highcolor, centercolor, lowcolor)
Thanks everyone.
To paint a MKPolyline with a gradient, you can use a custom subclass of MKPolylineView. As CoreGraphics does not support stroking a path with a gradient, we have to
convert the path to a shape that traces the paths edge using CGPathCreateCopyByStrokingPath
clip the context to that shape
fill using CGContextDrawLinearGradient
Here is a subclass to get you started:
#interface TWOGradientPolylineView : MKPolylineView
#end
#implementation TWOGradientPolylineView
- (void)strokePath:(CGPathRef)path inContext:(CGContextRef)context
{
CGFloat lineWidth = CGContextConvertSizeToUserSpace(context, (CGSize){self.lineWidth, self.lineWidth}).width;
CGPathRef pathToFill = CGPathCreateCopyByStrokingPath(path, NULL, lineWidth, self.lineCap, self.lineJoin, self.miterLimit);
CGRect rect = CGPathGetBoundingBox(pathToFill);
CGContextAddPath(context, pathToFill);
CGPathRelease(pathToFill);
CGContextClip(context);
CGFloat gradientLocations[2] = {0.0f, 1.0f};
CGFloat gradientColors[8] = {1.0f, 0.0f, 0.0f, 0.75f, 1.0f, 1.0f, 0.0f, 0.75f};
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
CGGradientRef gradient = CGGradientCreateWithColorComponents(colorSpace, gradientColors, gradientLocations, 2);
CGColorSpaceRelease(colorSpace);
CGPoint gradientStart = rect.origin;
CGPoint gradientEnd = {CGRectGetMaxX(rect), CGRectGetMaxY(rect)};
CGContextDrawLinearGradient(context, gradient, gradientStart, gradientEnd, kCGGradientDrawsAfterEndLocation);
CGGradientRelease(gradient);
}
#end
Here is a screenshot of a path drawn with the class above:
I have a UIView subclass on which the user can add a random CGPath. The CGPath is added by processing UIPanGestures.
I would like to resize the UIView to the minimal rect possible that contains the CGPath. In my UIView subclass, I have overridden sizeThatFits to return the minimal size as such:
- (CGSize) sizeThatFits:(CGSize)size {
CGRect box = CGPathGetBoundingBox(sigPath);
return box.size;
}
This works as expected and the UIView is resized to the value returned, but the CGPath is also "resized" proportionally resulting in a different path that what the user had originally drawn. As an example, this is the view with a path as drawn by the user:
And this is the view with the path after resizing:
How can I resize my UIView and not "resize" the path?
Use the CGPathGetBoundingBox. From Apple documentation:
Returns the bounding box containing all points in a graphics path. The
bounding box is the smallest rectangle completely enclosing all points
in the path, including control points for Bézier and quadratic curves.
Here a small proof-of-concept drawRect methods. Hope it helps you!
- (void)drawRect:(CGRect)rect {
//Get the CGContext from this view
CGContextRef context = UIGraphicsGetCurrentContext();
//Clear context rect
CGContextClearRect(context, rect);
//Set the stroke (pen) color
CGContextSetStrokeColorWithColor(context, [UIColor blackColor].CGColor);
//Set the width of the pen mark
CGContextSetLineWidth(context, 1.0);
CGPoint startPoint = CGPointMake(50, 50);
CGPoint arrowPoint = CGPointMake(60, 110);
//Start at this point
CGContextMoveToPoint(context, startPoint.x, startPoint.y);
CGContextAddLineToPoint(context, startPoint.x+100, startPoint.y);
CGContextAddLineToPoint(context, startPoint.x+100, startPoint.y+90);
CGContextAddLineToPoint(context, startPoint.x+50, startPoint.y+90);
CGContextAddLineToPoint(context, arrowPoint.x, arrowPoint.y);
CGContextAddLineToPoint(context, startPoint.x+40, startPoint.y+90);
CGContextAddLineToPoint(context, startPoint.x, startPoint.y+90);
CGContextAddLineToPoint(context, startPoint.x, startPoint.y);
//Draw it
//CGContextStrokePath(context);
CGPathRef aPathRef = CGContextCopyPath(context);
// Close the path
CGContextClosePath(context);
CGRect boundingBox = CGPathGetBoundingBox(aPathRef);
NSLog(#"your minimal enclosing rect: %.2f %.2f %.2f %.2f", boundingBox.origin.x, boundingBox.origin.y, boundingBox.size.width, boundingBox.size.height);
}