寫在最前面,閑來無事,恰逢接近過年,心情無比激動,但是作為一名碼農,絕對不能閑下來,故突發奇想,想做一個關于九宮格的手勢滑動解鎖,之前用過很多次,覺的酷酷噠,話不多說,下面進入正題
先上圖
作為一個好的程序猿,看到一個效果圖之后,我們首先做的是什么呢,恕在下愚見,當然不是盲目的去敲代碼,首先是分析問題,想想會用到什么技術,大概需要涉及到API,功能點都這么去實現呢,會用到什么模式呢,下面我就簡單分析下我在寫這個demo的時候的一些想法,若有什么不對的地方,請大神多多指教,技術總是在探討中進步
- 1 、分析問題
要實現該功能,難點在于,我們該怎么去實現線條的繪制。既然是手勢移動,那么我們肯定會在移動過程中一直進行繪制,這樣的話,我們就有兩種選擇:
1 touch事件 - (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
在移動過程中獲取位置坐標,然后進行繪制
2 UIPanGestureRecognizer 搖動或者拖拽手勢
移動的方式有了,那么我們還缺什么呢,當然是繪制線路的選擇方式,這里我們也有兩種方式
1、通過 UIBezierPath UIBezierPath 解釋:UIBezierPath是Core Graphics框架關于path的一個封裝。可以創建基于矢量的路徑,例如橢圓或者矩形,或者有多個直線和曲線段組成的形狀。 下面是簡單的繪制了一個矩形
- (void)drawRect:(CGRect)rect
{
UIColor *color = [UIColor colorWithRed:0 green:0 blue:0 alpha:1];
[color set]; //設置線條顏色
UIBezierPath* aPath = [UIBezierPath bezierPathWithRect:CGRectMake(120, 120, 100, 50)];
aPath.lineWidth = 5.0;
aPath.lineCapStyle = kCGLineCapRound; //線條拐角
aPath.lineJoinStyle = kCGLineCapRound; //終點處理
[aPath stroke];
}
2 、通過CGContext 或者 CGPath(路徑) 相信大家對CGContext比較熟悉也用的比較多,可以用來畫各種圖形,那么CGPath呢,我個人感覺和CGContext差不多,只是調用的方法可能不一樣
后面才發現,UIBezierPath其實就是對CGPathRef的封裝
下面為大家開啟三個傳送門,可以更好的了解了解
Core Graphics框架 : 一個讓程序猿成為視覺設計師的框架
Quartz 2D繪圖基礎:CGContextRef
CGContextRef,CGPath 和 UIBezierPath的區別
CGContextRef contextRef = UIGraphicsGetCurrentContext();
說完上面兩個方法后,下面就是怎么利用所繪制的路線呢?這里有兩個思路
1 我們可以將當前view上面加一個UIImageview,其大小和當前view一樣,我們在移動的時候,不停為其設置image,代碼如下
- (void)viewDidLoad
{
[super viewDidLoad];
self.drawLineImageView = [[UIImageView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:_drawLineImageView];
}
//根據顏色繪制圖片
- (UIImage *)imageWithColor:(UIColor *)color{
UIImage *image = nil;
if (self.addPasswords.count > 0)
{
UIButton * startButton = self.addPasswords[0];
UIGraphicsBeginImageContext(self.drawLineImageView.bounds.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetStrokeColorWithColor(context, color.CGColor);
CGContextSetLineWidth(context, 5);
CGContextMoveToPoint(context, startButton.center.x, startButton.center.y);
for (UIButton *button in self.addPasswords)
{
CGPoint point = button.center;
CGContextAddLineToPoint(context, point.x, point.y);
CGContextMoveToPoint(context, point.x, point.y);
}
CGContextAddLineToPoint(context, self.endPoint.x, self.endPoint.y);
CGContextStrokePath(context);
image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
return nil;
}
2 就是調用 - (void)drawRect:(CGRect)rect 函數,在view上繪制當前路徑,當然必須調用 [self setNeedsDisplay] ,來實時繪制
針對以上的方案,我選擇的是touch
事件和CGContext
并且設置圖片的image
的方法
寫在最后,希望到這里,對大家有一點點幫助,下面就為大家開啟傳送門,送上Demo,如有不好的地方,多多指教,如果你覺得好的話,可以star一個哦,功能包含兩次設置密碼,驗證密碼,效果圖如下