地图、轨迹绘制:
demo中使用timer模拟实时接收数据;
每次接收绘制点数(dataLength):6.8W-8W个;
已经使用BitMapContext对demo进行了优化,直接上代码:
func changeShape(dataArr: Array<JSON>, rect: CGRect){
let width = Int(rect.width)
let height = Int(rect.height)
// 位图的大小 = 图片宽 * 图片高 * 图片中每点包含的信息量
let imgByteCount = width * height * 4
// 使用系统的颜色空间
let colorSpace = CGColorSpaceCreateDeviceRGB()
// 计算总大小,申请内存空间
let shapeByteCount = width * height * 4
let shapeVoideData = malloc(shapeByteCount)
defer {free(shapeVoideData)}
let shapeData = unsafeBitCast(shapeVoideData, to: UnsafeMutablePointer<CUnsignedChar>.self)
for i in 0..<height {
for j in 0..<width {
let offset = ((height - i - 1)*width + j)*4
let pointee = dataArr[i*width + j].intValue
if pointee > 0 && pointee <= 70 {
(shapeData+offset).pointee = 255
(shapeData+offset+1).pointee = CUnsignedChar(16)
(shapeData+offset+2).pointee = CUnsignedChar(213)
(shapeData+offset+3).pointee = CUnsignedChar(161)
}else if pointee > 70 {
(shapeData+offset).pointee = 255
(shapeData+offset+1).pointee = CUnsignedChar(96)
(shapeData+offset+2).pointee = CUnsignedChar(219)
(shapeData+offset+3).pointee = CUnsignedChar(181)
}
}
}
// 创建位图
let imgContext = CGContext(data: shapeData,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
let outImage = imgContext?.makeImage()
// 绘制图片
DispatchQueue.main.async {
// 设置frame
self.frame = rect
self.image = UIImage(cgImage: outImage!)
}
}
是不是有疑问,为何申请内存空间的时候 width * height 还要再乘以4?
let imgContext = CGContext(data: shapeData,
width: width,
height: height,
bitsPerComponent: 8,
bytesPerRow: width * 4,
space: colorSpace,
bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue)
data: 创建BitmapContext所需的内存空间,由malloc创建
width: 图片的宽度
height: 图片的高度
bitsPerComponent: data中的每个数据所占的字节数
bytesPerRow: 图片每行的位数 = 图片列数*4(因为每个点有4个通道)
space: 颜色区间
bitmapInfo: bitmap类型,一般选择PremultipliedFirst(ARGB)
shapeData设置pointee的时候当然也要设置4次:
第一个值是alpha,设置固定值255,后三个是RGB。
(shapeData+offset).pointee = 255
(shapeData+offset+1).pointee = CUnsignedChar(96)
(shapeData+offset+2).pointee = CUnsignedChar(219)
(shapeData+offset+3).pointee = CUnsignedChar(181)
说了半天 大家可能还是不明白,这篇文章实现了什么需求:
通过一个一维数组,生成一张图片。
比如:
image.png
给我13338个点,可以生成一张宽114*高117的图片,点的内容是:
参考demo里,data.plist
[-1,0,1,2,-1 .....]
参考文章:http://ericasadun.com/?s=uikit
Git地址:https://github.com/kepingchang/OpenGLStudy
效果图:
preview-image.png
image.png
preview-drawMap.gif