基础:
工具:MAC ,Xcode
运用知识:MAC手势NSGestureRecognizer,自定义NSView,NSDrawer使用。
原理:
1.用手势类监控鼠标点击的坐标,存在数组中。鼠标点下为一条线的start点,结束为线的end点,把所有的点都穿进自定义View的数组中。
代码如下:
//视图点添加长按手势。
NSPressGestureRecognizer *ges = [[NSPressGestureRecognizer alloc]initWithTarget:self action:@selector(press:)];
ges.minimumPressDuration = 0.01;
[self.window.contentView addGestureRecognizer:ges];
//手势调用方法
//gesture
- (void)press:(NSGestureRecognizer *)ges{
NSPoint pt = [ges locationInView:self.window.contentView];
MutiPath *view = self.window.contentView;
//属性
//背景颜色
NSColor *bKColor = self.bkclr;
//线宽
float lineWidth = self.lineWidth ;
//线色
NSColor *lineClr = self.lineclr;
if(ges.state == NSGestureRecognizerStateBegan)//鼠标点下
{
NSLog(@"start");
[view drawMutiLinesInBackgroudColor:bKColor Point:pt withLineColor:lineClr LineWidth:lineWidth end:NO];
}else if(ges.state == NSGestureRecognizerStateChanged)//鼠标移动
{
NSLog(@"changed");
[view drawMutiLinesInBackgroudColor:bKColor Point:pt withLineColor:lineClr LineWidth:lineWidth end:NO];
}else if(ges.state == NSGestureRecognizerStateEnded)//鼠标松开
{
NSLog(@"ended");
[view drawMutiLinesInBackgroudColor:bKColor Point:pt withLineColor:lineClr LineWidth:lineWidth end:YES];
}
}
2.自定义View处理手段.所有的点保存进self.linesManage 里面存的对象为线模型,下面为线模型属性
#import@interface LineModel : NSObject
@property (nonatomic) NSColor *color;//线色
@property (nonatomic) NSArray *points;//线组成点
@property (nonatomic) BOOL isEnd;//线是否完结
@property (nonatomic) float lineWidth;//线宽
- (instancetype)init;
- (void)addpoint:(NSPoint) pt;
@end
自定义View中画线使用 NSBezierPath。
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
NSBezierPath *path = [NSBezierPath bezierPathWithRect:self.bounds];
if(!self.backgroud)
{
[[NSColor clearColor] set];
}else{
[self.backgroud set];
}
[path fill];
NSLog(@"drawRect");
if(self.linesManager.count !=0){
[self.linesManager enumerateObjectsUsingBlock:^(LineModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSArray *pts = obj.points;
if(pts.count > 1)
{
NSBezierPath *path = [NSBezierPath bezierPath];
path.lineWidth = obj.lineWidth;
[obj.color set];
[pts enumerateObjectsUsingBlock:^(NSString *ptstr, NSUInteger idx, BOOL * _Nonnull stop) {
NSPoint pt = NSPointFromString(ptstr);
if(idx ==0)
{
[path moveToPoint:pt];
}else
{
[path lineToPoint:pt];
[path stroke];
}
}];
}
}];}
}
3.工具抽屉类
//抽屉类初始化
- (void)drawerInit{
if(!self.dw)
{
self.dw = [[NSDrawer alloc]initWithContentSize:NSMakeSize(20, 40) preferredEdge:NSRectEdgeMinY];
self.dw.delegate = self;
ToolBar *tbar = [[ToolBar alloc]init];
tbar.delegate = self;
self.dw.contentView = tbar;
self.dw.parentWindow = self.window;
self.dw.leadingOffset = 0.f;
self.dw.trailingOffset = 0.f;
self.dw.minContentSize = NSMakeSize(100, 100);
self.dw.maxContentSize = NSMakeSize(300, 300);
[self.dw openOnEdge:NSRectEdgeMinY];
}
}
4.直接附图。
由于公司GitHub,CSND等网站均不能登录,实在抱歉源码发不出去,对mac感兴趣的同学可以留言,很乐意将源码提供大家一起学习进步。