ry *dic = @{@"x" : @(point.x), @"y": @(point.y)};
[tmp addObject:dic];
}
// 颜色类别
NSInteger colorNum = 0;
if (CGColorEqualToColor(self.drawView.color.CGColor, [UIColor redColor].CGColor)) {
colorNum = 1;
}
else if (CGColorEqualToColor(self.drawView.color.CGColor, [UIColor blueColor].CGColor) ){
colorNum = 2;
} else if (CGColorEqualToColor(self.drawView.color.CGColor, [UIColor greenColor].CGColor) ) {
colorNum = 3;
}
// 传递数据格式
NSDictionary *pathDataDict = @{
@"path" : tmp,
@"width" : @(self.drawView.width),
@"color" : @(colorNum),
@"screenW": @([UIScreen mainScreen].bounds.size.width),
@"screenH": @([UIScreen mainScreen].bounds.size.height)
};
NSData *pathData = [NSJSONSerialization
dataWithJSONObject:pathDataDict
options:NSJSONWritingPrettyPrinted
error:nil];
[self.clientSocket writeData:pathData
withTimeout:-1
tag:111111];
}
// 1、接受坐标点
NSInteger w = [tmpDict[@"screenW"] integerValue];
NSInteger h = [tmpDict[@"screenH"] integerValue];
CGFloat scaleW = [UIScreen mainScreen].bounds.size.width / w;
CGFloat scaleH = [UIScreen mainScreen].bounds.size.height / h;
// 处理点
NSArray *pointDict = tmpDict[@"path"];
DIYBezierPath *path = [[DIYBezierPath alloc]init];
for (NSDictionary *tmpDict in pointDict) {
CGPoint point = CGPointMake([tmpDict[@"x"] floatValue] * scaleW, [tmpDict[@"y"] floatValue] * scaleH);
NSInteger index = [pointDict indexOfObject:tmpDict];
if (index == 0) {
[path moveToPoint:point];
} else {
[path addLineToPoint:point];
}
}
switch ([tmpDict[@"color"] integerValue]) {
case 0:
self.drawView.color = [UIColor blackColor];
break;
case 1:
self.drawView.color = [UIColor redColor];
break;
case 2:
self.drawView.color = [UIColor blueColor];
break;
case 3:
self.drawView.color = [UIColor greenColor];
break;
default:
break;
}
self.drawView.width = [tmpDict[@"width"] floatValue];
self.drawView.currentPath = path;
self.drawView.currentPath.pathColor = self.drawView.color;
self.drawView.currentPath.lineWidth = self.drawView.width;
[self.drawView.pathArray addObject:path];
[self.drawView setNeedsDisplay];
五、小demo地址
https://github.com/HOWIE-CH/-You-guess-I-painted-_socket.git
六、问题
- 定义了图片文件二进制数据、笔画路径二进制数据、聊天字符串二进制数据,三种格式的二进制数据,在 GCDAsyncSocket 接受数据的代理方法,需要判断接受的二进制文件的类型再进行解析,如果有更好的方式可留言。
- 只是简单的功能的尝试,有时存在画的一条线过长就传输不过去的情况,存在图片偶尔传输不完整的情况
- 不清楚是否有相关成熟的框架,如果有,请留言。
- 最近试过服务端是 NodeJs 用 socket.io 的话,iOS 用 GCDAsyncSocket,感觉这样是通讯不了的。像这样要实现 Android、iOS 跨平台 socket 传输数据,那 socket 选择什么框架呢,服务端选择什么 socket 框架? 之前即时通讯都是 XMPP ,现在貌似是 webSocket socket.io 了。