首先,在iOS上绘制,你需要一个框架,并且在屏幕上绘制时,你不能得到drawRect:
(UIView的)或drawLayer:inContext:
(CALayer的)外的环境。这意味着选项3不存在(如果您打算在drawRect:
方法之外执行此操作)。
你可以去CALayer,但我会去这里的UIView。至于我明白你的设置,你有这样的:
UIScrollView
| | |
ViewA ViewB LineView
所以LineView是ViewA和ViewB的兄弟姐妹,就需要足够大,以涵盖ViewA和ViewB并且设置成在两个前(并有setOpaque:NO
集)。
LineView的实现将非常简单:给它两个CGPoint类型的属性point1
和point2
。也可以自己实施setPoint1:
/setPoint2:
方法,以便始终调用[self setNeedsDisplay];
,以便在点更改后重绘自身。
在LineView的drawRect:
中,您只需要用CoreGraphics或UIBezierPath来画线。哪一个使用或多或少是一个品味的问题。当你想使用CoreGraphics中,你做这样的:
- (void)drawRect:(CGRect)rect
{
CGContextRef context = UIGraphicsGetCurrentContext();
// Set up color, line width, etc. first.
CGContextMoveToPoint(context, point1);
CGContextAddLineToPoint(context, point2);
CGContextStrokePath(context);
}
使用NSBezierPath,它会看上去非常相似:
- (void)drawRect:(CGRect)rect
{
UIBezierPath *path = [UIBezierPath bezierPath];
// Set up color, line width, etc. first.
[path moveToPoint:point1];
[path addLineToPoint:point2];
[path stroke];
}
现在的魔术越来越为点1和点2的正确坐标。我假设你有一个可以看到所有视图的控制器。 UIView有两个很好的实用方法,您需要在这里输入convertPoint:toView:
和convertPoint:fromView:
。下面是控制器的虚拟代码,将导致LineView绘制ViewA和ViewB的中心之间的线:
- (void)connectTheViews
{
CGPoint p1, p2;
CGRect frame;
frame = [viewA frame];
p1 = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame));
frame = [viewB frame];
p2 = CGPointMake(CGRectGetMidX(frame), CGRectGetMidY(frame));
// Convert them to coordinate system of the scrollview
p1 = [scrollView convertPoint:p1 fromView:viewA];
p2 = [scrollView convertPoint:p2 fromView:viewB];
// And now into coordinate system of target view.
p1 = [scrollView convertPoint:p1 toView:lineView];
p2 = [scrollView convertPoint:p2 toView:lineView];
// Set the points.
[lineView setPoint1:p1];
[lineView setPoint2:p2];
[lineView setNeedsDisplay]; // If the properties don't set it already
}
因为我不知道你是如何实现拖动,我不能告诉你如何在控制器上触发调用此方法。如果它完全封装在你的视图中并且控制器没有涉及,那么我会为每次将视图拖动到新坐标时发布的NSNotification。控制器会监听通知并调用上述方法来更新LineView。
最后一个注意事项:您可能需要在您的LineView的initWithFrame:
方法中调用setUserInteractionEnabled:NO
,以便线上的触摸将通过该线下的视图。
快乐编码!
+1是最有效的方法,但计算正确的位置和转换比使用简单的绘图解决方案(UIView或CALayer)更难。给定两点* p1 *和* p2 *,如何正确定位/旋转图层?我有一些想法,但都没有感觉“正确”。 – DarkDust 2011-05-01 11:56:07
@DarkDust添加代码以显示如何设置图层属性。 – 2011-05-01 14:26:25
@Niklai Ruhe:谢谢,这比我想象的更简单。 – DarkDust 2011-05-01 14:43:10