【发布时间】:2015-01-19 16:24:43
【问题描述】:
我想创建一个模拟速度计的 UIView。我创建了一个新类 SpeedometerView 并将其链接到我的主视图上的 UIView。然后使用下面的代码,我创建了一个类似于速度计的图像。
#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
现在的问题是我想将值传递给这个类以根据速度移动指针。为此,我已经设置了 gX 和 gY 的值,但我不确定如何继续。将值发送到 SpeedometerView 的代码如下,我只是不确定如何每次刷新 SpeedometerView。
-(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];
});
}
【问题讨论】:
-
运行代码时会发生什么? setNeedsDisplay 绝对是用于重绘视图 - 您不应该使用静态 gX、gY 等,而是以某种方式将其作为数据模型的一部分并在重绘时从视图中访问它......
标签: ios xcode core-graphics cgrect