【发布时间】:2013-03-27 20:33:03
【问题描述】:
我有一个非常简单(希望非常简单)的问题。在 Objective-C 中,如何在两点之间画一条线并将其添加到 UIView?我曾尝试使用 UIImageView 并操作其 Transform 属性,但在使用以下代码时最终会将线变成正方形或矩形:
[[self tline] setFrame:CGRectMake(start.x, start.y, width, 5)];
[[self tline] setTransform:CGAffineTransformMakeRotation(angle)];
我有两个 CGPoints,start 和 end,我想在两个点之间画一条动态的 5px 线并将其添加到我的子视图中。
BK:
start 点是用户开始触摸屏幕的点,end 点是用户手指当前所在的点。显然,这会在游戏过程中发生很大变化。我需要能够移动这条线来连接这两点。
我正在使用touchesBegan:, Moved:, and Ended: 方法来创建、移动和销毁线路。
核心图形
我有以下代码;如何将此行添加到self.view?
CGContextRef c = UIGraphicsGetCurrentContext();
CGFloat color[4] = {1.0f, 1.0f, 1.0f, 0.6f};
CGContextSetStrokeColor(c, color);
CGContextBeginPath(c);
CGContextMoveToPoint(c, start.x, start.y);
CGContextAddLineToPoint(c, end.x, end.y);
CGContextSetLineWidth(c, 5);
CGContextSetLineCap(c, kCGLineCapRound);
CGContextStrokePath(c);
自定义 UIView:
#import <UIKit/UIKit.h>
@interface DrawingView : UIView
@property (nonatomic) CGPoint start;
@property (nonatomic) CGPoint end;
- (void)drawRect:(CGRect)rect;
@end
#import "DrawingView.h"
@implementation DrawingView
- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
}
return self;
}
- (void)drawRect:(CGRect)rect {
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSaveGState(context);
CGContextSetLineCap(context, kCGLineCapSquare);
CGContextSetStrokeColorWithColor(context, [UIColor whiteColor].CGColor); //change color here
CGFloat lineWidth = 5.0; //change line width here
CGContextSetLineWidth(context, lineWidth);
CGPoint startPoint = [self start];
CGPoint endPoint = [self end];
CGContextMoveToPoint(context, startPoint.x + lineWidth/2, startPoint.y + lineWidth/2);
CGContextAddLineToPoint(context, endPoint.x + lineWidth/2, endPoint.y + lineWidth/2);
CGContextStrokePath(context);
CGContextRestoreGState(context);
NSLog(@"%f",_end.x);
}
- (void)setEnd:(CGPoint)end
{
_end = end;
[self setNeedsDisplay];
}
@end
drawRect: 仅在我初始化视图时调用...
UIViewController 中的绘制方法:
- (void)drawTLine:(CGPoint)start withEndPoint:(CGPoint)end
{
[[self dview] setStart:start];
[[self dview] setEnd:end];
[[self dview] drawRect:[self dview].frame];
}
这是我添加绘图视图的方式:
DrawingView* dview = [[DrawingView alloc] initWithFrame:self.view.frame];
[dview setBackgroundColor:[UIColor clearColor]];
[self.view addSubview:dview];
【问题讨论】:
-
你考虑过 Core Graphics,使用 UIView 的
draw:方法吗? -
如果我使用 draw 方法,我将如何跟踪线条?我需要能够根据需要移动、调整大小和销毁它。
-
在你移动的事件中,你也许可以更新一个属性/变量来跟踪当前位置。每次更新都会调用
draw:方法,因此您只需在开始和当前之间画一个点,并删除所有旧线。清理很简单,就像这里的大纲一样 -> stackoverflow.com/a/7907669/1415949 -
Gabriele 的答案应该可以很好地工作,只要你画直线
-
两件事;如何将其实现到 UIViewController 的视图中,以及如何调用此方法?我需要给它两个 CGPoints 来划清界限。
标签: ios objective-c uiview uitouch