ios - 在自定义 UIView 中绘制圆圈

标签 ios uiview

我有一个带有 drawRect 的自定义 UIView:

-(void)drawRect:(CGRect)rect{

CGContextRef context = UIGraphicsGetCurrentContext();
[self drawControlPointsWithCoordsX:point.x andY:point.y forRect:CGRectMake(0, 0, 320, 600) andContext:context];
NSLog(@"Values: %f and %f", point.x, point.y);

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
    [self  startTimer];
});
}

[自启动计时器];是启动方法。在这种方法中,我启动了一个计时器,它会产生一些纵坐标对。它只被调用一次。坐标以这种形式出现:

值:276.711670 和 117.279999

一直在变化。记录所有值。在定时器每 0.1 秒重复一次的方法中,我调用:

[self drawRect:CGRectMake(0, 0, 320, 600)];

日志有效,坐标不断变化,并且是正确的,但只绘制了两个或三个点(而不是大约 400 个)并且它们位于错误的位置。

这是绘制点的代码:

- (void)drawControlPointsWithCoordsX:(int)x andY:(int)y forRect:(CGRect)rect andContext:(CGContextRef)contextRef
{
UIGraphicsPushContext(contextRef);
CGContextSetLineWidth(contextRef, 2.0);
CGContextSetRGBFillColor(contextRef, 0, 0, 1.0, 1.0);
CGContextSetRGBStrokeColor(contextRef, 0, 0, 1.0, 1.0);
CGRect circlePoint = (CGRectMake(x,y, 5.0, 5.0));

CGContextFillEllipseInRect(contextRef, circlePoint);
}

最佳答案

首先,您不应该手动调用 drawRect:,因为它会在通知重绘 View 时自动调用。因此,如果您选择像这样手动重绘它,行为可能是未定义的,因为当前图形上下文可能不同或无效。以下内容摘自 Apple 关于 drawRect: 方法的文档:

This method is called when a view is first displayed or when an event occurs that invalidates a visible part of the view. You should never call this method directly yourself. To invalidate part of your view, and thus cause that portion to be redrawn, call the setNeedsDisplay or setNeedsDisplayInRect: method instead.

此外,您可能不应该在 drawRect: 中启动运行的计时器。您可能应该从其他地方启动计时器,例如代码中您首次显示此 View 的地方。同样,每次重绘 View 时,它都会清除之前存在的内容,而不是覆盖它。因此,如果您希望它建立在之前绘制的内容之上,您必须跟踪您绘制的每个点并重新绘制所有它们直到当前点。您可以通过其他方式完成此操作,无需重新绘制您已经绘制的内容,但会更加复杂。

关于ios - 在自定义 UIView 中绘制圆圈,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20665774/

相关文章:

ios - xib 的 UIView 模糊

swift - 通过按下按钮更新 UIView

ios - 照片框架和可重用的 UICollectionViewCell

iOS 应用程序存在加密提交问题

ios - 使用 SpriteKit 的分屏 2 人本地多人游戏

ios - 如何限制 UICollectionView 中的可选单元格

iphone - 两次调用 removeFromSuperview 会导致崩溃或副作用

ios - 如何使用索引(:) with [SomeProtocol]?

iphone - 我该怎么做才能调整 UIView 的大小以适合其 subview ?

ios - 使用UIImage放大UIView而不影响UIImage的分辨率