照例我们先看看效果图

怎么样?效果很不错吧,下面来一起看看实现的过程和代码示例。
实现原理
从图中可以大致看出,爆炸点点都是取的某坐标的颜色值,然后根据一些动画效果来完成的。
取色值
怎么取的view的某个点的颜色值呢?google一下,就可以找到很多答案。就不具体说了。创建1*1的位图,然后渲染到屏幕上,然后得到RGBA。我这里写的是UIView的extension。
extension UIView {
public func colorOfPoint(point:CGPoint) -> UIColor
{
var pixel:[CUnsignedChar] = [0,0,0,0]
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.PremultipliedLast.rawValue)
let context = CGBitmapContextCreate(&pixel, 1, 1, 8, 4, colorSpace, bitmapInfo.rawValue)
CGContextTranslateCTM(context, -point.x, -point.y)
self.layer.renderInContext(context!)
let red: CGFloat = CGFloat(pixel[0]) / 255.0
let green: CGFloat = CGFloat(pixel[1]) / 255.0
let blue: CGFloat = CGFloat(pixel[2]) / 255.0
let alpha: CGFloat = CGFloat(pixel[3]) / 255.0
return UIColor(red:red, green: green, blue:blue, alpha:alpha)
}
}
粒子的生成
这里我写的比较简单,就是固定每个粒子大小,根据View的宽高算出横向,纵向的粒子数,取该点的色值,设置粒子背景色,然后生成即可。
主要代码如下:
frameDict是我预先计算好的坐标表,colorDict是颜色表。以"i-j"为key
class func createExplosionPoints(containerLayer: ExplosionLayer, targetView: UIView, animationType: ExplosionAnimationType) {
let hCount = self.caculatePointHCount(containerLayer.targetSize.width)
let vCount = self.caculatePointVCount(containerLayer.targetSize.height)
for i in 0..<hCount {
for j in 0..<vCount {
let key = String(format: "%d-%d", i, j)
if let rect = containerLayer.frameDict[key], color = containerLayer.colorDict[key] {
let layer = createExplosionPointLayer(rect, bgColor: color, targetViewSize: containerLayer.targetSize)
// animation
layer.explosionAnimation = self.createAnimationWithType(animationType, position: layer.position, targetViewSize: containerLayer.targetSize)
containerLayer.addSublayer(layer)
layer.beginAnimation()
}
}
}
}
动画效果
每个粒子都有一个CAAnimation动画,数据由调用者提供,灵活点。
这里定义了一个protocol:ExplosionAnimationProtocol ,可以自定义实现了该protocol的动画对象,提供动画效果。










