【问题标题】:core graphics, how to draw lines at runtime?核心图形,如何在运行时画线?
【发布时间】:2012-04-06 12:29:12
【问题描述】:

任务是,在运行时在我在 Scrollview 中使用的自定义地图上绘制路径,然后每当位置坐标(纬度、经度)更新时,我必须在运行时绘制路径。我在这里试图解决的问题是我创建了一个类“图形”,它是 UIView 的子类,我在“drawrect:”方法中对绘图进行编码。因此,当我将图形添加为图像上滚动视图的子视图时,线条会绘制,但我需要继续绘制线条,就好像它是路径一样。我需要在运行时画线,需要不断更新'CGContextStrokeLineSegments'方法的points(x,y)。代码:

视图控制器:

- (void)loadView {
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:UIStatusBarAnimationNone];
CGRect fullScreenRect=[[UIScreen mainScreen] applicationFrame];
scrollView=[[UIScrollView alloc] initWithFrame:fullScreenRect];
graph = [[graphics alloc] initWithFrame:fullScreenRect];
scrollView.contentSize=CGSizeMake(320,480);

UIImageView *tempImageView2 = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"fortuneCenter.png"]];

self.view=scrollView;
[scrollView addSubview:tempImageView2];
scrollView.userInteractionEnabled = YES;
scrollView.bounces = NO;
[scrollView addSubview:graph];
}

图形.m:

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
    // Initialization code
    self.backgroundColor = [UIColor clearColor];
}
return self;
}

- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
CGPoint point [2] = { CGPointMake(160, 100), CGPointMake(160,300)};
CGContextSetRGBStrokeColor(context, 255, 0, 255, 1);
CGContextStrokeLineSegments(context, point, 2);
}

那么我如何在运行时画线。我现在只是在模拟,所以我没有使用实时数据(坐标)。只想使用虚拟数据(x,y 的坐标)进行模拟。假设有一个按钮,每当我按下它时,它都会更新坐标,因此路径会延伸。

【问题讨论】:

    标签: iphone ios ios4 xcode4.2


    【解决方案1】:

    最简单的方法是将代表点的实例变量添加到UIView 子类。 然后,每次路径更改时,适当地更新 ivar 并在自定义 UIView(甚至在其父视图)上调用 -setNeedsDisplaysetNeedsDisplayInRect。然后运行时将重绘新路径。

    【讨论】:

      【解决方案2】:

      您只需要让CGPoint point[] 看起来可以动态调整大小。

      您可以使用mallocstd::vector,甚至NSMutableData 来存储您添加的积分。然后将该数组传递给CGContextStrokeLineSegments

      如果您只需要 2 个点,请将 CGPoint point[2] 移动到 ivar,以便您可以存储位置,然后(如 Rich 所述)在这些值(或数组)更改时适当地使 rect 无效。

      【讨论】:

        【解决方案3】:

        这个主题时不时出现,所以我创建了一篇较长的博客文章,介绍与一种潜在解决方案有关的一般概念,创建和使用您自己的图形上下文,这里:http://www.musingpaw.com/2012/04/drawing-in-ios-apps.html

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-02-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多