问题描述
|
我在学习时尝试构建一些iOS应用程序,但在理解执行此操作的正确方法时遇到了一些麻烦。
我目前所拥有的是一个视图,它是UIView的子类。很清楚,我想将其用作绘图表面。它将位于其他内容之上,例如描图纸。
用户应该能够单击一个点,然后单击另一个点,并且应该在两个点之间画一条线。我正在获取触摸数据,有了要点,并且能够从drawRect内部绘制东西:最初。
问题是我不确定以后如何更新内容。当所有内容加载完毕并调用drawRect:时,它将绘制一条直线。但是,如何根据用户的操作来绘制新内容或更改已经绘制的内容。我知道我需要调用setNeedsdisplay,但不需要调用数据到视图来绘制内容。
我已经读了一堆教程/示例,它们都停在\“ Override drawRect:并绘制一些内容...完成!\”。我如何将数据向下传递到视图以告诉它“嘿,重绘此内容并添加此新行”。
还是我会以错误的方式进行处理?
编辑:
我将尝试更好地解释我的设置。
我有一个VC。在该VC \的视图中,我在底部有一个工具栏。该区域的其余部分被2个景观占据。一种是保存参考图像的图像视图。一种是位于顶部的清晰自定义视图(描图纸)。他们单击工具栏上的按钮以打开手势识别器。他们在屏幕上单击,然后我收集点击数据,关闭手势识别器,然后很高兴地画一条线。除了绘图部分,我已经全部工作了。
解决方法
您走在正确的轨道上。听起来您需要跟踪要点。
这是一些示例代码。
LineDrawView.h
#import <UIKit/UIKit.h>
@interface LineDrawView : UIView
{
NSMutableArray *lines;
CGPoint pointA,pointB;
BOOL activeLine;
}
@end
LineDrawView.m
#import \"LineDrawView.h\"
@implementation LineDrawView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self)
{
self.backgroundColor = [UIColor blackColor];
lines = [[NSMutableArray alloc] init];
}
return self;
}
- (void)dealloc
{
[lines release];
[super dealloc];
}
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesBegan:touches withEvent:event];
CGPoint point = [[touches anyObject] locationInView:self];
if ([lines count] == 0) pointA = point;
else pointB = point;
activeLine = YES;
}
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesMoved:touches withEvent:event];
pointB = [[touches anyObject] locationInView:self];
[self setNeedsDisplay];
}
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
[super touchesEnded:touches withEvent:event];
pointB = [[touches anyObject] locationInView:self];
[lines addObject:[NSArray arrayWithObjects:[NSValue valueWithCGPoint:pointA],[NSValue valueWithCGPoint:pointB],nil]];
pointA = pointB;
pointB = CGPointZero;
activeLine = NO;
[self setNeedsDisplay];
}
- (void)drawRect:(CGRect)rect
{
CGContextRef c = UIGraphicsGetCurrentContext();
CGContextSetLineWidth(c,2);
CGContextSetLineCap(c,kCGLineCapRound);
CGContextSetLineJoin(c,kCGLineJoinRound);
CGContextSetStrokeColorWithColor(c,[UIColor grayColor].CGColor);
for (NSArray *line in lines)
{
CGPoint points[2] = { [[line objectAtIndex:0] CGPointValue],[[line objectAtIndex:1] CGPointValue] };
CGContextAddLines(c,points,2);
}
CGContextStrokePath(c);
if (activeLine)
{
CGContextSetStrokeColorWithColor(c,[UIColor whiteColor].CGColor);
CGPoint points2[2] = { pointA,pointB };
CGContextAddLines(c,points2,2);
CGContextStrokePath(c);
}
}
@end