Ios 我想在现有的UIView上绘制一个图形
我想创建一个模拟车速表的UIView。我创建了一个新类SpeedMeterView,并将其链接到主视图上的UIView。然后使用下面的代码,我创建了一个类似于车速表的图像Ios 我想在现有的UIView上绘制一个图形,ios,xcode,core-graphics,cgrect,Ios,Xcode,Core Graphics,Cgrect,我想创建一个模拟车速表的UIView。我创建了一个新类SpeedMeterView,并将其链接到主视图上的UIView。然后使用下面的代码,我创建了一个类似于车速表的图像 #import "SpeedometerView.h" @implementation SpeedometerView static int gX = 57; static int gY = 180; - (void)drawRect:(CGRect)rect { CGContextRef contextRef =
#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值,但我不确定如何继续。下面是将值发送到SpeedMeterView的代码,我只是不确定每次如何刷新SpeedMeterView
-(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];
});
}
您需要更改SpeedMeterView的gX和gY。执行此操作时,将调用setNeedsDisplay和drawInRect:。关键是更改这些值,这将在使用绘图方法绘制UIView时反映出来。您可以实现一个观察者来监听更改或使用NSNotifications并将车速表刷新到更新的值 使用属性而不是静态 您可以在drawRect:中访问这些: 您可以访问updateSpeed,如下所示:
运行代码时会发生什么?setNeedsDisplay绝对是用于重画视图的-您不应该使用静态gX,gY,所以,但应该以某种方式使数据模型成为一部分,并在重画时从视图中访问它。。。
@interface SpeedometerView : ...
@property int gX = 57;
@property int gY = 180;
@end
- (void)drawRect:(CGRect)rect {
// ...
CGContextAddLineToPoint(contextRef, self.gX, self.gY);
// ...
}
- (void)updateSpeed {
// ...
dispatch_async(dispatch_get_main_queue(), ^{
if (resultVSC > 0)
self.mphOutput.text = [[NSString alloc] initWithFormat:@"%d Mph", resultVSC];
self.view.gX = appDelegate.gX;
self.view.gY = 180 + resultVSC;
[self.view setNeedsDisplay];
});
}