Search code examples
iosxcodecore-graphicscgrect

I want to draw a graphic over my existing UIView


I want to create a UIView that emulates a Speedometer. I've created a new class SpeedometerView and linked it to a UIView on my main view. Then using the code below I've created an image that resembles a speedometer.

#import "SpeedometerView.h"

@implementation SpeedometerView
static int gX = 57;
static int gY = 180;

- (void)drawRect:(CGRect)rect
{
    CGContextRef contextRef = UIGraphicsGetCurrentContext();

    CGContextFillEllipseInRect(contextRef, CGRectMake(135, 105, 10, 10));
    CGContextSetRGBFillColor(contextRef, 0, 0, 255, 1.0);

    CGContextStrokeEllipseInRect(contextRef, CGRectMake(30, 0, 220, 220));
    CGContextSetRGBFillColor(contextRef, 0, 0, 255, 1.5);

    CGContextSetStrokeColorWithColor(contextRef, [[UIColor redColor] CGColor]);
    CGContextSetLineWidth(contextRef, 3.0);
    CGContextMoveToPoint(contextRef, 140.0, 110.0);
    CGContextAddLineToPoint(contextRef, gX, gY);

    CGContextDrawPath(contextRef, kCGPathStroke);

    CGContextSetFillColor(contextRef, CGColorGetComponents([UIColor redColor].CGColor));

    CGContextBeginPath(contextRef);
    CGContextMoveToPoint(contextRef, gX, gY);
    CGContextAddLineToPoint(contextRef, gX + 1, gY - 5);
    CGContextAddLineToPoint(contextRef, gX + 5, gY - 1);
    CGContextClosePath(contextRef);
    CGContextDrawPath(contextRef, kCGPathFillStroke);
}

@end

The issue now is that I want to pass values to this class to move the needle according to the speed. I've set the values gX and gY for this purpose but I'm unsure how to proceed. The code that will send the values to SpeedometerView is below, I'm just unsure how to refresh SpeedometerView each time.

-(void) updateSpeed
{
    AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
    appDelegate.gX = 50 + resultVSC;
    appDelegate.gY = 180 - resultVSC;
    dispatch_async(dispatch_get_main_queue(), ^{
    if (resultVSC > 0)
        self.mphOutput.text = [[NSString alloc] initWithFormat:@"%d Mph", resultVSC];
    //Update SpeedometerView??
    [self.view setNeedsDisplay];
    });
}

Solution

  • You need to change the SpeedometerView's "gX" and "gY". When you do that, call "setNeedsDisplay" and drawInRect: will be called. The key is to change those values and this will be reflected when drawing the UIView in the drawing method.