[英]How can I draw dynamic rectangle on screen according to touchMove event on iOS
矩形將被視為兩個點,第一個點將是touchBegan點,在touchMove上將是第二個點,將根據用戶的手指移動來動態繪制矩形(例如,當您在桌面上單擊並移動鼠標時鼠標,您將獲得動態矩形)。
謝謝
UIView
子類,例如DrawingView
在DrawingView
您應該實現以下方法:
將起點保存在方法中- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
在此處重繪- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
在此處隱藏rect(或將其保存) - (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
和此處- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
例如,在第一種方法中,您可以通過以下方式檢測起點:
CGPoint startCornerOfYourRect;
for (UITouch *touch in touches)
{
startCornerOfYourRect = [touch locationInView:self];
break;
}
好的,這是在touchesMoved
繪制矩形的方法(使用@Nekto touchesBegan
存儲矩形的起點)。
假設您在要繪制的UIView上保留一個引用,並將其drawnView
。 在touchesBegan
,我們為drawnView
設置框架的drawnView
這是touchesMoved
:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent*)event
{
// We only take care of a single touch
if ([touches count] == 1)
{
UITouch *touch = [touches anyObject];
// Find the width and height of the rect
CGRect drawnFrame = drawnView.frame
drawnFrame.size.width = [touch locationInView:parentView].x - drawnFrame.origin.x
drawnFrame.size.height = [touch locationInView:parentView].y - drawnFrame.origin.y
[drawnView setFrame:drawnFrame];
}
}
不要復制粘貼該代碼,我也沒有用Xcode或任何東西編寫它。 它可能有錯誤(肯定)。 但我希望它可以幫助您找到解決方案。 請注意,如果您將手指拖到頂部或左側(高度和寬度的負值),我將無法知道它的行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.