[英]How to drag a line in ios using UIPanGestureRecognizer
我正在編寫一個程序,用戶將一條線從一個UILabel
拖到另一個。 我創建了一個名為DragView的UIView
子類,並覆蓋了drawRect
方法。 我將UIView
RootController
視圖的子視圖。 DragView
是絕對可見的, drawRect
方法是絕對被調用的,但是沒有一行可見。
這些是(我認為是)相關的代碼段。
//DragView.m
- (void)drawRect:(CGRect)rect
{
if (context == nil)
{
context = UIGraphicsGetCurrentContext();
}
if (_drawLineFlag)
{
CGContextSetLineWidth(context,2.0);
CGColorSpaceRef colorspace = CGColorSpaceCreateDeviceRGB();
CGFloat components[] = {0.0,0.0,1.0,1.0};
CGColorRef color = CGColorCreate(colorspace, components);
CGContextSetStrokeColorWithColor(context,color);
CGContextMoveToPoint(context,_startX, _startY);
CGContextAddLineToPoint(context,_currentX,_currentY);
CGContextStrokePath(context);
}
}
DrawProgramAppDelegate
- (void) initializeUI
{
.....
dragView = [[DragView alloc] initWithFrame:CGRectMake(0.0f,0.0f,1024.0f,768.0f)] ;
[view addSubview: dragView];
UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(handlePan:)];
[dragView addGestureRecognizer:panGestureRecognizer];
.....
}
事件處理程序為:
- (void) handlePan:(UIPanGestureRecognizer *) recognizer
{
CGPoint point = [recognizer translationInView:dragView];
[dragView setCurrentX:point.x];
[dragView setCurrentY:point.y];
[dragView setDrawLineFlag:YES];
[view bringSubviewToFront:drawView];
[dragView drawRect:CGRectMake (0.0f,0.0f,768.0f, 1024.0f)];
}
非常感謝您的幫助。
喬恩
在我看來,您正在嘗試畫一條路(您應該看一下這篇文章 )。 在這里,您似乎只是從最后一點到當前點畫一條線
CGContextMoveToPoint(context,_startX, _startY);
CGContextAddLineToPoint(context,_currentX,_currentY);
給定通話頻率只會畫一條小線。
您不應該調用drawRect:
[dragView drawRect:CGRectMake (0.0f,0.0f,768.0f, 1024.0f)];
您應該告訴系統視圖需要顯示
[dragView setNeedsDisplay];
另外,您還應該檢查手勢識別器狀態,定義為
typedef enum {
UIGestureRecognizerStatePossible,
UIGestureRecognizerStateBegan,
UIGestureRecognizerStateChanged,
UIGestureRecognizerStateEnded,
UIGestureRecognizerStateCancelled,
UIGestureRecognizerStateFailed,
UIGestureRecognizerStateRecognized = UIGestureRecognizerStateEnded
} UIGestureRecognizerState;
並且可能僅在狀態為UIGestureRecognizerStateChanged
或UIGestureRecognizerStateEnded
繪制
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.