NSBezierPath Graph - objective-c

I cannot figure out how to optimize the drawing of an NSView that contains a NSBezierPath.
Let me try to explain what I mean. I have a line graph, made by about 40K points, that I want to draw. I have all the points and it's easy for me to draw once the full graph using the following code:
NSInteger npoints=[delegate returnNumOfPoints:self]; //get the total number of points
aRange=NSMakeRange(0, npoints); //set the range
absMin=[delegate getMinForGraph:self inRange:aRange]; //get the Minimum y value
absMax=[delegate getMaxForGraph:self inRange:aRange]; //get the Maximum y value
float delta=absMax-absMin; //get the height of bound
float aspectRatio=self.frame.size.width/self.frame.size.heigh //compensate for the real frame
float xscale=aspectRatio*(absMax-absMin); // get the width of bound
float step=xscale/npoints; //get the unit size
[self setBounds:NSMakeRect(0.0, absMin, xscale, delta)]; //now I can set the bound
NSSize unitSize={1.0,1.0};
unitSize= [self convertSize:unitSize fromView:nil];
[NSBezierPath setDefaultLineWidth:MIN(unitSize.height,unitSize.width)];
fullGraph=[NSBezierPath bezierPath];
[fullGraph moveToPoint:NSMakePoint(0.0, [delegate getValueForGraph:self forPoint:aRange.location])];
//Create the path
for (long i=1; i<npoints; i++)
{
y=[delegate getValueForGraph:self forPoint:i];
x=i*step;
[fullGraph lineToPoint:NSMakePoint(x,y)];
}
[[NSColor redColor] set];
[fullGraph stroke];
So now I have the whole graph stored in a NSBezierPath form in real coordinate, that I can stroke. But let's suppose that now I want to display the graph adding one point at time as fast as possible.
I do not want to draw the whole set of points every time. I want to use, if possible the complete graph and visualize only a small part. Let's say that I want to render in the same frame only the first 1000 points. Is there any possibility (modifying bounds and eventually scaling the path in some way) to render only the first part of the graph in correct bounds?
I was not able to obtain the result, because if I modify the bounds then the scale changes and I'm not able to fix the problem with linewidth.

You can create a new path with just the new data, stroke it, then append that to your existing graph:
NSBezierPath* newPath = [NSBezierPath bezierPath];
//... draw the new lines in newPath ...
[newPath stroke];
[fullGraph appendBezierPath:newPath];

Related

UIBezierPath of a circle and rectangle intersection for a mask

I am trying to create a mask region of the intersection of a circle and a rectangle.
I am starting with this code that seems to create an XOR of the circle and rectangle for the mask region but I want just a plain old AND:
- (void)addMaskToHoleViewAtX:(CGFloat) x AtY:(CGFloat) y Radius:(CGFloat) kRadius {
CGRect bounds = holeView.bounds;
CAShapeLayer *maskLayer = [CAShapeLayer layer];
maskLayer.frame = bounds;
maskLayer.fillColor = [UIColor blackColor].CGColor;
CGRect const rect = CGRectMake(CGRectGetMidX(bounds) - kRadius/2,
CGRectGetMidY(bounds) - kRadius,
kRadius,
2 * kRadius);
UIBezierPath *pathrect = [UIBezierPath bezierPathWithRect:rect];
CGRect const circ = CGRectMake(CGRectGetMidX(bounds) - kRadius,
CGRectGetMidY(bounds) - kRadius,
2 * kRadius,
2 * kRadius);
UIBezierPath *pathcirc= [UIBezierPath bezierPathWithOvalInRect:circ];
UIBezierPath *allPaths= [[UIBezierPath alloc] init];
[allPaths appendPath:pathrect];
[allPaths appendPath:pathcirc];
[allPaths appendPath:[UIBezierPath bezierPathWithRect:bounds]];
maskLayer.path = allPaths.CGPath;
maskLayer.fillRule = kCAFillRuleEvenOdd;
holeView.layer.mask = maskLayer;
holeView.center = CGPointMake(x, y);
}
Could someone help me with the syntax to do the AND, I think I might need to use addClip but it is not obvious to me how to do that with the above code?
MY SOLUTION: It appears to me that if I were able to figure how to use addClip to solve this problem in one manner, I would not actually end up with the closed NSBezierPath of the intersection. I prefer not to do it that way as having the intersection NSBezierPath is also needed to easily determine if a point is inside the path. SOOOO, I just created the NSBezierPath of the intersection through calculations and used my derived path to append to the masklayer bounds path. It sure would be nice to have a way of actually obtaining the intersection NSBezierPath without calculations but I just had to move on. Thanks for trying.
Thanks,
Carmen
EDIT : Here is the routine I am calling to put the 'intersection' mask over my _map View. Change _map to your view if you want to try this:
- (void)addHoleSubview {
holeView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 10000, 10000)];
holeView.backgroundColor = [UIColor colorWithRed:255 green:0 blue:0 alpha:0.2];
holeView.autoresizingMask = 0;
[_map addSubview:holeView];
[self addMaskToHoleViewAtX:100 AtY:100 Radius:50];
}
If you aim for the intersection of two paths you should not create a compound path. Appending a path to another path will
result in a union of both paths if using the non-zero winding number rule and both paths have the same direction - or in other words it will have the effect of an AND
result in a shape that contains only the parts of the areas surrounded by the two paths that do not overlap if using the even-odd rule - or in other words it will have the effect of an XOR.
Instead I suggest you first add the first path pathrect to your graphics context and clip
[pathrect addClip];
and then you add the second path pathcirc to your context and clip again:
[pathcirc addClip];
You can now use any filling rule within that context and it will fill the intersection (the AND) of the two paths.

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];
}

Drawing board/grid with Cocoa

I'm writing a small boardgame for Mac OS X using Cocoa. I the actual grid is drawn as follows:
- (void)drawRect:(NSRect)rect
{
for (int x=0; x < GRIDSIZE; x++) {
for (int y=0; y < GRIDSIZE; y++) {
float ix = x*cellWidth;
float iy = y*cellHeight;
NSColor *color = (x % 2 == y % 2) ? boardColors[0] : boardColors[1];
[color set];
NSRect r = NSMakeRect(ix, iy, cellWidth, cellHeight);
NSBezierPath *path = [NSBezierPath bezierPath];
[path appendBezierPathWithRect:r];
[path fill];
[path stroke];
}
}
}
This works great, except that I see some errors in colors between the tiles. I guess this is due to some antialiasing or similar. See screenshots below (hopefully you can also see the same problems... its some black lines where the tiles overlap):
Therefore I have these questions:
Is there any way I can remove these graphical artefacts while still maintaining a resizable/scalable board?
Should I rather use some other graphical library like Core Graphics or OpenGL?
Update:
const int GRIDSIZE = 16;
cellWidth = (frame.size.width / GRIDSIZE);
cellHeight = (frame.size.height / GRIDSIZE);
If you want crisp rectangles you need to align coordinates so that they match the underlying pixels. NSView has a method for this purpose: - (NSRect)backingAlignedRect:(NSRect)aRect options:(NSAlignmentOptions)options. Here's a complete example for drawing the grid:
const NSInteger GRIDSIZE = 16;
- (void)drawRect:(NSRect)dirtyRect {
for (NSUInteger x = 0; x < GRIDSIZE; x++) {
for (NSUInteger y = 0; y < GRIDSIZE; y++) {
NSColor *color = (x % 2 == y % 2) ? [NSColor greenColor] : [NSColor redColor];
[color set];
[NSBezierPath fillRect:[self rectOfCellAtColumn:x row:y]];
}
}
}
- (NSRect)rectOfCellAtColumn:(NSUInteger)column row:(NSUInteger)row {
NSRect frame = [self frame];
CGFloat cellWidth = frame.size.width / GRIDSIZE;
CGFloat cellHeight = frame.size.height / GRIDSIZE;
CGFloat x = column * cellWidth;
CGFloat y = row * cellHeight;
NSRect rect = NSMakeRect(x, y, cellWidth, cellHeight);
NSAlignmentOptions alignOpts = NSAlignMinXNearest | NSAlignMinYNearest |
NSAlignMaxXNearest | NSAlignMaxYNearest ;
return [self backingAlignedRect:rect options:alignOpts];
}
Note that you don't need stroke to draw a game board. To draw pixel aligned strokes you need to remember that coordinates in Cocoa actually point to lower left corners of pixels. To crisp lines you need to offset coordinates by half a pixel from integral coordinates so that coordinates point to centers of pixels. For example to draw a crisp border for a grid cell you can do this:
NSRect rect = NSInsetRect([self rectOfCellAtColumn:column row:row], 0.5, 0.5);
[NSBezierPath strokeRect:rect];
First, make sure your stroke color is not black or gray. (You're setting color but is that stroke or fill color? I can never remember.)
Second, what happens if you simply fill with green, then draw red squares over it, or vice-versa?
There are other ways to do what you want, too. You can use the CICheckerboardGenerator to make your background instead.
Alternately, you could also use a CGBitmapContext that you filled by hand.
First of all, if you don't actually want your rectangles to have a border, you shouldn't call [path stroke].
Second, creating a bezier path for filling a rectangle is overkill. You can do the same with NSRectFill(r). This function is probably more efficient and I suspect less prone to introduce rounding errors to your floats – I assume you realize that your floats must not have a fractional part if you want pixel-precise rectangles. I believe that if the width and height of your view is a multiple of GRIDSIZE and you use NSRectFill, the artifacts should go away.
Third, there's the obvious question as to how you want your board drawn if the view's width and height are not a multiple of GRIDSIZE. This is of course not an issue if the size of your view is fixed and a multiple of that constant. If it is not, however, you first have to clarify how you want the possible remainder of the width or height handled. Should there be a border? Should the last cell in the row or column take up the remainder? Or should it rather be distributed equally among the cells of the rows or columns? You might have to accept cells of varying width and/or height. What the best solution for your problem is, depends on your exact requirements.
You might also want to look into other ways of drawing a checkerboard, e.g. using CICheckerboardGenerator or creating a pattern color with an image ([NSColor colorWithPatternImage:yourImage]) and then filling the whole view with it.
There's also the possibility of (temporarily) turning off anti-aliasing. To do that, add the following line to the beginning of your drawing method:
[[NSGraphicsContext currentContext] setShouldAntialias:NO];
My last observation is about your general approach. If your game is going to have more complicated graphics and animations, e.g. animated movement of pieces, you might be better off using OpenGL.
As of iOS 6, you can generate a checkerboard pattern using CICheckerboardGenerator.
You'll want to guard against the force unwraps in here, but here's the basic implementation:
var checkerboardImage: UIImage? {
let filter = CIFilter(name: "CICheckerboardGenerator")!
let width = NSNumber(value: Float(viewSize.width/16))
let center = CIVector(cgPoint: .zero)
let darkColor = CIColor.red
let lightColor = CIColor.green
let sharpness = NSNumber(value: 1.0)
filter.setDefaults()
filter.setValue(width, forKey: "inputWidth")
filter.setValue(center, forKey: "inputCenter")
filter.setValue(darkColor, forKey: "inputColor0")
filter.setValue(lightColor, forKey: "inputColor1")
filter.setValue(sharpness, forKey: "inputSharpness")
let context = CIContext(options: nil)
let cgImage = context.createCGImage(filter.outputImage!, from: viewSize)
let uiImage = UIImage(cgImage: cgImage!, scale: UIScreen.main.scale, orientation: UIImage.Orientation.up)
return uiImage
}
Apple Developer Docs
Your squares overlap. ix + CELLWIDTH is the same coordinate as ix in the next iteration of the loop.
You can fix this by setting the stroke color explicitly to transparent, or by not calling stroke.
[color set];
[[NSColor clearColor] setStroke];
or
[path fill];
// not [path stroke];

Drawing a CGPath UIBezierCurve

Hi all I am looking into ways of how I can draw a shape like the one in the illustration above.I have been looking and reading but getting slightly confused of how curves are drawn using UIBezierPath. I found really nice code which uses CAShapeLayer with animation to draw lines.
The code so far I have is :
#synthesize animationLayer = _animationLayer;
#synthesize pathLayer = _pathLayer;
#synthesize penLayer = _penLayer;
- (void) setupDrawingLayer
{
if (self.pathLayer != nil) {
[self.penLayer removeFromSuperlayer];
[self.pathLayer removeFromSuperlayer];
self.pathLayer = nil;
self.penLayer = nil;
}
CGPoint upperCurve = CGPointMake(101, 100);
CGPoint lowerCurve = CGPointMake(224,200);
UIBezierPath *path = [UIBezierPath bezierPath];
path.lineCapStyle = kCGLineCapRound;
path.miterLimit = -10.0f;
path.lineWidth = 10.0f;
[path moveToPoint:lowerCurve];
[path addQuadCurveToPoint:upperCurve controlPoint:lowerCurve];
CAShapeLayer *pathLayer = [CAShapeLayer layer];
pathLayer.frame = self.animationLayer.bounds;
pathLayer.path = path.CGPath;
pathLayer.strokeColor = [[UIColor blackColor] CGColor];
pathLayer.fillColor = nil;
pathLayer.lineWidth = 10.0f;
pathLayer.lineJoin = kCALineJoinBevel;
[self.animationLayer addSublayer:pathLayer];
self.pathLayer = pathLayer;
}
-(void) startAnimation
{
[self.pathLayer removeAllAnimations];
CABasicAnimation *pathAnimation = [CABasicAnimation animationWithKeyPath:#"strokeEnd"];
pathAnimation.duration = 10.0;
pathAnimation.fromValue = [NSNumber numberWithFloat:0.0f];
pathAnimation.toValue = [NSNumber numberWithFloat:1.0f];
[self.pathLayer addAnimation:pathAnimation forKey:#"strokeEnd"];
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.animationLayer = [CALayer layer];
self.animationLayer.frame = CGRectMake(20.0f, 64.0f,
CGRectGetWidth(self.view.layer.bounds) - 40.0f,
CGRectGetHeight(self.view.layer.bounds) - 84.0f);
[self.view.layer addSublayer:self.animationLayer];
[self setupDrawingLayer];
[self startAnimation];
}
The way I solve this kind of problem is to draw the shape in a drawing program such as Illustrator. This shows clearly where the bezier curve points need to go in order to get the curve I'm after.
A UIBezierPath generally starts with moveToPoint to set the starting point of the curve. Then it's followed by any number of curve segments using these methods:
– addLineToPoint:
– addArcWithCenter:radius:startAngle:endAngle:clockwise:
– addCurveToPoint:controlPoint1:controlPoint2:
– addQuadCurveToPoint:controlPoint:
You didn't state specifically what you're having trouble with, so I'm going to make a leap and assume it is addCurveToPoint:controlPoint1:controlPoint2 that you are struggling with.
The segment added by this call draws a segment starting at the most recently added or moved to point in the curve to the first argument. How it undulates is determined by the control points.
The simplest way to understand how it undulates is to imagine lines connecting the first point (established in the previous method call) to the first control point (let's call this control point line segment 1), and another line connecting the first argument (ending point of the segment being added) to the second control point (let's call this control point line segment 2).
The Bezier curve at the starting point is tangent to control point line segment 1. It is tangent to control point line segment 2 at the end of the curve.
So if you want to draw a curve with multiple Beziers such that they form a smooth line, you need to make sure that the slope of control point line segment 2 of one curve is the same as the slope of control point line segment 1 of the next curve that joins to it.
The distances from the starting point to the first control point, and the ending point to the second control point determine the curvature of the curve.
A friend of mine imagines it this way. Imagine a space ship traveling from point A to point B. The space ship starts out with a heading determined by the slope of control point line segment 1 and a speed determined by its length. The heading is gradually changed to the slope of control point line segment 2. Meanwhile, the speed is gradually changed to the length of of control point line segment 2. By the time the space ship arrives at point B, it is traveling tangent to that segment.

UIView coordinate systems - offsetting and translating

I'm pretty sure this is more a of a math question, but I'll phrase it in the context of UIView and iPad-related objective C
I am importing raw data from a mapping file I have created from some public domain material downloaded elsewhere, then split out to isolate various regions within the map. Each region has a number of sub-regions, much like, for example, the continental US and then the various states which appear within the US, and then each sub-region is broken down again, into, let's say, counties.
Each state, and each county has a bounding box which tells me the origin, the width, and height each is.
In my initial setup, I created a separate view for each state, and then another view for each county. The polygon representing the area of the state/county was rendered (obviously with the county on top of the state so it would be visible) relative to a view I created through interface builder, called mainContainerView. This initial setup worked correctly.
Now I am trying to change things a bit, by adding the counties to the UIView holding the polygon for the state, so I will be able to overlay the state as a clipping mask on the counties. The problem is that no matter what I try, I cannot seem to get the county to translate to the right place within the state's view.
It seems like it should be straightforward addition or subtraction as the scaling for each item is exactly the same, and I'm not trying to do any major transformations, so I do not believe the CFAffineTransformation family is needed.
I can post code if necessary, but I'm not trying to get someone to write my program for me; I just want someone to point me in the right direction here, by giving me a suggestion on how to set the county relative to the state within the state's view.
As per a request, here's the relevant code that I am working on right now. This code does not work, but it gives you the idea as to what I'm doing. Posting sample data is a little more difficult, as it involves arrays of points and data extracted from a .SHP file designed to produce a map (and subdivisions). I'll include some comments in the code with some real point values as I step through the program to show you what's happening to them.
MASK_MAX_EASTING, MASK_MAX_NORTHING, MASK_MIN_EASTING, and MASK_MIN_NORTHING are constants which define the bounding box for the entire map of the country when made up of states.
DIST_MAX_EASTING, DIST_MAX_NORTHING, DIST_MIN_EASTING, and DIST_MIN_NORTHING are constants which define the bounding box for a map of the country when made up of the counties. The scales of the two maps are slightly different, so, by using the different bounding boxes, I've been able to scale the two maps to the same size.
-(void)didLoadMap:(NSNotification *)notification {
id region = [notification object];
ShapePolyline *polygon = [region polygon];
if ([notification name] == #"MapsLoadingForState") {
// m_nBoundingBox is an array which contains the RAW northing and easting values for each subdivision. [0] - west limit, [1] - south limit, [2] - east limit, [3] - north limit.
// The code below, combined with the drawrect method in DrawMap.m (below) puts all the states on the map in precisely the right places, so for the state maps, it works just fine.
CGFloat originX = ((polygon->m_nBoundingBox[0]-MASK_MIN_EASTING)*stateScaleMultiplier)+([mainContainerView frame].size.width/2);
CGFloat originY = ((MASK_MAX_NORTHING-(polygon->m_nBoundingBox[3]))*stateScaleMultiplier)+[mainContainerView frame].origin.y;
CGFloat width = polygon->m_nBoundingBox[2] - polygon->m_nBoundingBox[0];
CGFloat height = polygon->m_nBoundingBox[3] - polygon->m_nBoundingBox[1];
CGFloat scaledWidth = width*stateScaleMultiplier;
CGFloat scaledHeight = height*stateScaleMultiplier;
UIColor *subViewColor = [UIColor colorWithRed:0.0 green:1.0 blue:1.0 alpha:0.0];
stateMapView = [[DrawMap alloc] initWithFrame:CGRectMake(originX, originY, scaledWidth, scaledHeight)];
[stateMapView setBackgroundColor:subViewColor];
[stateMapView setStateScale:stateScaleMultiplier];
[stateMapView setCountyScale:countyScaleMultiplier]; // Not actually needed.
[stateMapView setClippingMask:polygon];
UIColor *colorMask = [UIColor colorWithWhite:1.0 alpha:1.0];
[stateMapView setForeground:colorMask];
[states addObject:stateMapView]; // Add the state map view to an array (for future use)
[mapView addSubview:stateMapView]; // MapView is a UIView of equivalent size and shape as mainContainerView.
} else {
// This is where the problems occur.
CGFloat originX = (polygon->m_nBoundingBox[0]-DIST_MIN_EASTING); // 4431590 (raw data)
originX *= countyScaleMultiplier; // 303.929108
originX += ([mainContainerView frame].size.width/2); // 815.929077
CGFloat originY = (DIST_MAX_NORTHING-polygon->m_nBoundingBox[3]); 4328997
originY *= countyScaleMultiplier; // 296.893036
originY -= [mainContainerView frame].origin.y; // 340.893036
CGRect frame = [stateMapView frame]; // Dummy variable created for watches in the debugger. x=856.237183, y=332.169922 width=34.3800087, height=28.7534008
// When I was invoking DrawMap.h and the included drawrect method, the county map would easily be displayed in the right place, as you can see by the values above.
// This is where I think the problem is. The X value is WAY off as far as I can tell.
originX -= frame.origin.x; // -40.3081055
originY -= frame.origin.y; // 8.72311401
CGPoint countyOrigin = CGPointMake(originX,originY);
// Translate the county's origin so it is relative to the origin of stateMapView, not MainContainerView (doesn't work)
[stateMapView addCountyMap:[region polygon] withColor:winner translatedBy:countyOrigin];
[stateMapView setNeedsDisplay];
}
I am aware that there are several issues with this code and some stuff outside the scope of this question may make a few of you raise an eyebrow (or two) but this is definitely a work in progress...
Here's the relevant code from DrawMap.m; I've cut a bunch of stuff out because it is extraneous.
- (void)drawRect:(CGRect)rect {
// Set up
for (int i=0;i<[countyMaps count];i++) {
// Draw the polygon.
[[countyColors objectAtIndex:i] setFill];
[self drawPolygon:[countyMaps objectAtIndex:i]
usingScale:stateScale
translatedBy:CGPointMake([[countyTranslations objectAtIndex:2*i] floatValue],
[[countyTranslations objectAtIndex:2*i+1] floatValue])];
}
// Set the blend mode to multiply
CGContextSetBlendMode(context, kCGBlendModeMultiply);
// Draw a path with clippingMask
[[UIColor colorWithWhite:1.0 alpha:1.0] setFill];
// CGPoint translate = CGPointMake(0,0);
[self drawPolygon:clippingMask usingScale:stateScale translatedBy:CGPointMake(0,0)];
}
-(void)drawPolygon:(ShapePolyline *)aPolygon usingScale:(float)mapScale translatedBy:(CGPoint)trans {
for (int j=0;j<[aPolygon numParts];j++) {
UIBezierPath *path = [UIBezierPath bezierPath];
[path setLineJoinStyle:kCGLineJoinRound];
int startIndex = [[[aPolygon m_Parts] objectAtIndex:j] intValue];
int endIndex = [aPolygon numPoints];
CGPoint startPoint;
[[[aPolygon m_Points] objectAtIndex:startIndex] getValue:&startPoint];
startPoint.x *=mapScale;
startPoint.y *=mapScale;
startPoint.x -= trans.x;
startPoint.y -= trans.y;
[path moveToPoint:startPoint];
if (j+1 != [aPolygon numParts]){
endIndex = [[[aPolygon m_Parts] objectAtIndex:j+1] intValue];
}
for (int k=startIndex+1; k<endIndex; k++)
{
CGPoint nextPoint;
[[[aPolygon m_Points] objectAtIndex:k] getValue:&nextPoint];
nextPoint.x *= mapScale;
nextPoint.y *= mapScale;
nextPoint.x -= trans.x;
nextPoint.y -= trans.y;
[path addLineToPoint:nextPoint];
}
[path closePath];
// [path stroke];
[path fill];
}
}
This tome is really may be too much information, or it may not be enough. Either way, hopefully by adding code, I've given you some information to go on...
-SOLVED-
And it was so simple. I'm surprised it took me this long to figure it out, as I was right in my initial question - it was simple addition and subtraction:
All translations are now done inside the methods which render the polygons. For each point in the polygon, I needed to add the origin of the state's view, and subtract the origin of the county's bounding box, then subtract 44 from the Y-value (the height of the control bar).
This, I think, is an example of over-thinking a problem, getting frustrated, over-thinking more, only to find out three days later that the answer is staring you in the face, waving a red flag, and shouting, "I'M OVER HERE!!!!"