iOS CoreGraphics: Draw arc, determine arc angles from intersecting chord theorem - objective-c

I'm trying to figure out how to draw an arc in CoreGraphics. I understand which method calls to make and how to compute the angles in the following scenario.
----------
| |
*--------*
When the points are both in the bottom of the rect. However when two points are in other locations, I don't know how to calculate the correct angle.
---------*
| |
*---------
See bottom portion of my image.
Ray Wenderlich has a great tutorial about creating arcs for only in the first mentioned point positions.
// sample code for creating arc for path from bottom of rect
CGMutablePathRef createArcPathFromBottomOfRect(CGRect rect, CGFloat arcHeight) {
CGRect arcRect = CGRectMake(rect.origin.x, rect.origin.y + rect.size.height
- arcHeight, rect.size.width, arcHeight);
CGFloat arcRadius = (arcRect.size.height/2) + (pow(arcRect.size.width, 2) /
(8 * arcRect.size.height));
CGPoint arcCenter = CGPointMake(arcRect.origin.x + arc.size.width/2,
arcRect.origin.y + arcRadius);
CGFloat angle = acos(arcRect.size.width/ (2*arcRadius));
CGFloat startAngle = radians(180) + angle;
CGFloat endAngle = radians(360) - angle;
CGMutablePathRef path = CGPathCreateMutable();
CGPathAddArc(path, NULL, arcCenter.x, arcCenter.y, arcRadius, startAngle,
endAngle, 0);
return path;
}
How do I calculate the angle when in other situations as depicted at the bottom of my image?

I find an easier way to make arcs is to use:
void CGContextAddArcToPoint (
CGContextRef c,
CGFloat x1,
CGFloat y1,
CGFloat x2,
CGFloat y2,
CGFloat radius
);
If you look at this image from Ray Wenderlich's site (https://www.raywenderlich.com/33330/core-graphics-tutorial-glossy-buttons), point (x1,y1) is your start point for the curve and point (x2,y2) is your end point. Then just specify the corner radius and voila! It looks like this may be an easier API to use for what you are looking to do.

You need at least 3 points to determine a circle.
In your first senario where two points are at the bottom of a rect, the top middle point is implicitly the third point when arcHeight is known. Therefore the three points determined the circle, thus the arc. So all angles and etc can be calculated.
In you second senario however, no third point is defined. Therefore you can draw infinite number of arcs passing through the two points with different curvatures. You will need additional requirements to fixed an arc. For example the radius or a third point supposed to be one the arc.

Related

Drawing a Speedometer with Core Graphics on OSX in NSView

I'm trying draw elements of a Speed Gauge using Core Graphics on OSX. I've almost got it but need a little bit of help on the center ticks inside of the gauge. Here is the image of what I'm trying to do:
Here is an image of what I've got so far:
I know how to draw the circle rings and how to draw segments based around the center of the gauge like this:
- (void)drawOuterGaugeRingsInRect:(CGContextRef)contextRef rect:(NSRect)rect {
CGContextSetLineWidth(contextRef,self.gaugeRingWidth);
CGContextSetStrokeColorWithColor(contextRef, [MyColors SpeedGaugeOuterRingGray].CGColor);
CGFloat startRadians = 0;
CGFloat endRadians = M_PI*2;
CGFloat radius = self.bounds.size.width/2 - 5;
CGContextAddArc(contextRef, CGRectGetMidX(rect),CGRectGetMidY(rect),radius,startRadians,endRadians,YES);
//Render the outer gauge
CGContextStrokePath(contextRef);
//Draw the inner gauge ring.
radius -= self.gaugeRingWidth;
CGContextSetStrokeColorWithColor(contextRef, [MyColors SpeedGaugeInnerRingGray].CGColor);
CGContextAddArc(contextRef, CGRectGetMidX(rect),CGRectGetMidY(rect),radius,startRadians,endRadians,YES);
//Render the inner gauge
CGContextStrokePath(contextRef);
radius -= self.gaugeRingWidth;
//Draw and fill the gauge background
CGContextSetFillColorWithColor(contextRef, [MyColors SpeedGaugeCenterFillBlack ].CGColor);
CGContextSetStrokeColorWithColor(contextRef, [MyColors SpeedGaugeCenterFillBlack].CGColor);
CGContextAddArc(contextRef, CGRectGetMidX(rect),CGRectGetMidY(rect),radius,startRadians,endRadians,YES);
//Render and fill the gauge background
CGContextDrawPath(contextRef, kCGPathFillStroke);
/*BLUE CIRCULAR DIAL */
//Prepare to draw the blue circular dial.
radius -= self.gaugeRingWidth/2;
//Adjust gauge ring width
CGContextSetLineWidth(contextRef,self.gaugeRingWidth/2);
CGContextSetStrokeColorWithColor(contextRef, [MyColors SpeedGaugeBlue].CGColor);
CGFloat startingRadians = [MyMathHelper degressToRadians:135];
CGFloat endingRadians = [MyMathHelper degressToRadians:45];
CGContextAddArc(contextRef, CGRectGetMidX(rect),CGRectGetMidY(rect),radius,startingRadians,endingRadians,NO);
//Render the blue gauge line
CGContextStrokePath(contextRef);
}
The code above is called in the drawRect: method in my NSView
The key section is the code here:
- (void)drawInnerDividerLines:(CGContextRef)context rect:(NSRect)rect {
CGFloat centerX = CGRectGetMidX(rect);
CGFloat centerY = CGRectGetMidY(rect);
CGContextSetLineWidth (context, 3.0);
CGContextSetRGBStrokeColor (context, 37.0/255.0, 204.0/255.0, 227.0/255.0, 0.5);
CGFloat destinationX = centerX + (centerY * (cos((135)*(M_PI/180))));
CGFloat destinationY = centerY + (centerX * (sin((135)*(M_PI/180))));
NSPoint destinationPoint = NSMakePoint(destinationX, destinationY);
CGContextMoveToPoint(context, centerX, centerY);
CGContextAddLineToPoint(context, destinationPoint.x, destinationPoint.y);
CGContextStrokePath(context);
}
I understand what is going on here but the problem I'm trying to solve is drawing the little lines, off of the inner blue line that extend toward the center point of the View, but do not draw all the way to the center. I'm a little unsure on how to modify the math and drawing logic to achieve this. Here is the unit circle I based the angles off of for Core Graphics Drawing.
The main problems I'm trying to solve are:
How to define the proper starting point off of the light blue inner line as a staring point for each gauge tick. Right now, I'm drawing the full line from the center to the edge of the gauge.
How to control the length of the tick gauge as it draws pointed toward the center off of it's origin point on the blue line.
Any tips or advice that would point in me in the right direction to solve this would be appreciated.
I recommend using vectors. You can find a line to any point on the circle given an angle by calculating:
dirX = cos(angle);
dirY = sin(angle);
startPt.x = center.x + innerRadius * dirX;
startPt.y = center.y + innerRadius * dirY;
endPt.x = center.x + outerRadius * dirX;
endPt.y = center.y + outerRadius * dirY;
You can then plot a line between startPt and endPt.
Any tips or advice that would point in me in the right direction to solve this would be appreciated.
Given a point on the circumference of your circle at a certain angle around the centre you can form a right angled triangle, the radius is the hypotenuse, and the other two sides being parallel to the x & y axes (ignore for a moment the degenerate case where the point is at 0, 90, 180 or 270 deg). Given that with the sin & cos formula (remember SOHCAHTOA from school) and some basic math you can calculate the coordinates of the point, and using that draw a radius from the centre to the point.
The end points of a "tick" mark just lie on circles of different radii, so the same math will give you the end points and you can draw the tick. You just need to decide the radii of these circles, i.e. the distance along your original radius the end points of the tick should be.
HTH
Another approach to avoid the trigonometry is to rotate the transformation matrix and just draw a vertical or horizontal line.
// A vertical "line" of width "width" along the y axis at x==0.
NSRect tick = NSMakeRect(-width / 2.0, innerRadius, width, outerRadius - innerRadius);
NSAffineTransform* xform = [NSAffineTransform transform];
// Move the x and y axes to the center of your speedometer so rotation happens around it
[xform translateXBy:center.x yBy:center.y];
// Rotate the coordinate system so that straight up is actually at your speedometer's 0
[xform rotateByDegrees:135];
[xform concat];
// Create a new transform to rotate back around for each tick.
xform = [NSAffineTransform transform];
[xform rotateByDegrees:-270.0 / numTicks];
for (int i = 0; i < numTicks; i++)
{
NSRectFill(tick);
[xform concat];
}
You probably want to wrap this in [NSGraphicsContext saveGraphicsState] and [NSGraphicsContext restoreGraphicsState] so the transformation matrix is restored when you're done.
If you want two different kinds of tick marks (major and minor), then have two different rects and select one based on i % 10 == 0 or whatever. Maybe also toggle the color. Etc.

What is wrong with this way of using CGAffineTransform?

I want to make a graph in a UIView that shows numerical data. So I need to draw axis, a few coordinate lines, some tick marks, and then the data as connected straight lines. The data might typically consist of a few hundred x values in the range -500. to +1000. with corresponding y values in the range 300. to 350.
So I thought a good approach would be to transform the coordinates of the UIView so (for the example values given) the left side of the view is -500, and right side is 1000, the top is 400 and the bottom is 300. And y increases upwards. Then in drawRect: I could write a bunch of CGContextMoveToPoint() and CGContextAddLineToPoint() statements with my own coordinate system and not have to mentally translate each call to the UIView coordinates.
I wrote the following function to generate my own CGContextRef but it doesn't do what I expected. I've been trying variations on it for a couple days now and wasting so much time. Can someone say how to fix it? I realize I can't get clear in my mind whether the transform is supposed to specify the UIView coordinates in terms of my coordinates, or vice versa, or something else entirely.
static inline CGContextRef myCTX(CGRect rect, CGFloat xLeft, CGFloat xRight, CGFloat yBottom, CGFloat yTop) {
CGAffineTransform ctxTranslate = CGAffineTransformMakeTranslation(xLeft, rect.size.height - yTop);
CGAffineTransform ctxScale = CGAffineTransformMakeScale( rect.size.width / (xRight - xLeft), -rect.size.height / (yTop - yBottom) ); //minus so y increases toward top
CGAffineTransform combinedTransform = CGAffineTransformConcat(ctxTranslate, ctxScale);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextConcatCTM(c, combinedTransform);
return c;
}
The way I'm using this is that inside drawRect I just have:
CGContextRef ctx = myCTX(rect, self.xLeft, self.xRight, self.yBottom, self.yTop);
and then a series of statements like:
CGContextAddLineToPoint(ctx, [x[i] floatValue], [y[i] floatValue]);
I figured this out by experimenting. The transform requires 3 steps instead of 2 (or, if not required, at least it works this way):
static inline CGContextRef myCTX(CGRect rect, CGFloat xLeft, CGFloat xRight, CGFloat yBottom, CGFloat yTop) {
CGAffineTransform translate1 = CGAffineTransformMakeTranslation(-xLeft, -yBottom);
CGAffineTransform scale = CGAffineTransformMakeScale( rect.size.width / (xRight - xLeft), -rect.size.height / (yTop - yBottom) );
CGAffineTransform transform = CGAffineTransformConcat(translate1, scale);
CGAffineTransform translate2 = CGAffineTransformMakeTranslation(1, rect.size.height);
transform = CGAffineTransformConcat(transform, translate2);
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextConcatCTM(c, transform);
return c;
}
You use this function inside drawRect. In my case the xLeft, xRight, etc. values are properties of a UIView subclass and are set by the viewController. So the view's drawRect looks like so:
- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSaveGState(c);
CGContextRef ctx = myCTX(rect, self.xLeft, self.xRight, self.yBottom, self.yTop);
…
all of the CGContextMoveToPoint(), CGContextAddLineToPoint(), calls to
draw your desired lines, rectangles, curves, etc. but not stroke or fill them
…
CGContextRestoreGState(c);
CGContextSetLineWidth(c, 1);
CGContextStrokePath(c);
}
The CGContextSetLineWidth call isn't needed if you want a line width of 1. If you don't restore the graphics state before strokePath the path width is affected by the scaling.
Now I have to figure out how to draw text onto the view.

How do I get the angle to which I want to rotate UIView

The red line is UIView that is rotating with anchor point at its center. What I want to achieve is that when I drag my finger around that green circle holding it on the red circle, that red line goes along with the finger. But I can't do that without knowing the angle. How do I count it?
You can use the Pythagorean theorem to calculate the radius. In this case you know that the center of the circle is at x:152, y:0. Your touch location would be at x1, y1, which gives you enough information to calculate the legs.
In code:
CGPoint center = CGPointMake(152.0f, 0.0f);
CGPoint touchPoint = [gestureRecognizer locationInView:yourView];
float xLeg = fabs(center.x - touchPoint.x);
float yLeg = fabs(touchPoint.y);
angle = atan(xLeg / yLeg);
//float radius = sqrt(pow(xLeg, 2) + pow(yLeg, 2));
Hope it helps!
Note: Edited to reflect change of wording. Original question asked for radius.
use the arctangent of 3 points. (center, the point, where touch started/ or a fixed position that you define as angle 0 , the current touch point )
double AngleBetweenThreePoints(CGPoint point1,CGPoint point2, CGPoint point3)
{
CGPoint p1 = CGPointMake(point2.x - point1.x, -1*point2.y - point1.y *-1);
CGPoint p2 = CGPointMake(point3.x -point1.x, -1*point3.y -point1.y*-1);
double angle = atan2(p2.x*p1.y-p1.x*p2.x,p1.y*p2.y);
return angle /(2* M_PI);
}

How to draw an elliptical arc with CoreGraphics?

Is it possible to draw an elliptical arc like SVG path, in CoreGraphics and how?
I ran into the same thing tonight. CG doesn't offer an easy way to draw a non-circular arc, but you can do it using CGPath and a suitable transformation matrix. Suppose you want an arc of an axis-aligned ellipse starting at left,top and with a size of width,height. Then you can do something like this:
CGFloat cx = left + width*0.5;
CGFloat cy = top + height*0.5;
CGFloat r = width*0.5;
CGMutablePathRef path = CGPathCreateMutable();
CGAffineTransform t = CGAffineTransformMakeTranslation(cx, cy);
t = CGAffineTransformConcat(CGAffineTransformMakeScale(1.0, height/width), t);
CGPathAddArc(path, &t, 0, 0, r, startAngle, endAngle, false);
CGContextAddPath(g->cg, path);
CGContextStrokePath(g);
CFRelease(path);
Note that if you want to draw a pie-shaped wedge, then just surround the "CGContextAddPath" call with a CGContextMoveToPoint(cx,cy) and a CGContextAddLineToPoint(cx,cy), and use CGContextFillPath instead of CGContextStrokePath. (Or if you want to fill and stroke at the same time, use CGContextDrawPath.)

Find destination position of ball

How to move the ball dependent on touch angle and make the ball reflect if it touches the wall?
CGFloat diffX = ballImg.position.x - tchLoc.x;
CGFloat diffY = ballImg.position.y - tchLoc.y;
CGFloat angleRadian = atan2f(diffY, diffX);
float angleDegrees=CC_RADIANS_TO_DEGREES(angleRadian);
I am considering that you have taken your ball as a sprite. so in touchesBegan you will get the touch location and then you can use that location points in CCMoveTo action to move your ball which is a sprite.....