偶然發(fā)現(xiàn)了一個(gè)好玩的類, CADisplayLink,出于好奇所以就嘗試了一下,用 CADisplayLink 做了個(gè)類似云飄的效果。由于對(duì) CADisplayLink 的認(rèn)識(shí)還比較淺,如果哪里寫的不正確,還請(qǐng)各位大大能夠指出來(lái)!看效果圖先,
就是有點(diǎn)丑,??

ning.gif
- 核心代碼如下:
一、創(chuàng)建 CADisplayLink,添加事件,綁定 Runloop。
// 創(chuàng)建 CADisplayLink
- (CADisplayLink *)displayLink {
if (!_displayLink) {
_displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(makeCloud)];
// 當(dāng)把 CADisplayLink 對(duì)象添加到 Runloop 中后,selector就能被周期性調(diào)用
[self.displayLink addToRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
}
return _displayLink;
}
// 周期調(diào)用的方法
- (void)makeCloud {
self.cloudOffsetX += self.cloudSpeed;
[self cloudLayerName:self.firstCloudLayer];
[self cloudLayerName:self.secondCloudLayer];
[self cloudLayerName:self.thirdCloudLayer];
[self cloudLayerName:self.fourthCloudLayer];
[self cloudLayerName:self.fifthCloudLayer];
}
二、配置參數(shù),加載圖層
self.cloudWidth = self.frame.size.width; // 云彩寬度
self.cloudColor = RGBA(255, 255, 255, 0.3); // 云彩顏色
self.cloudSpeed = 0.05 / M_PI; // 云彩飄動(dòng)的速度
self.cloudPointY = 100; // 云彩Y坐標(biāo)
self.cloudOffsetX = 0; // 云彩位移X
self.cloudAmplitude = 30; // 振幅大小
self.cloudCycle = 1.03 * M_PI / self.cloudWidth; // 周期大小
// 添加圖層
[self.layer addSublayer:self.firstCloudLayer];
[self.layer addSublayer:self.secondCloudLayer];
[self.layer addSublayer:self.thirdCloudLayer];
[self.layer addSublayer:self.fourthCloudLayer];
[self.layer addSublayer:self.fifthCloudLayer];
三、創(chuàng)建 CAShapeLayer 動(dòng)畫
// 五個(gè)圖層動(dòng)畫
- (void)cloudLayerName:(CAShapeLayer *)cloudLayerName {
// 創(chuàng)建一個(gè)Path句柄
CGMutablePathRef path = CGPathCreateMutable();
CGFloat y = self.cloudPointY;
// 初始化該path到一個(gè)初始點(diǎn)
CGPathMoveToPoint(path, nil, 0, y);
for (float x = 0.0f; x <= self.cloudWidth; x++) {
if (cloudLayerName == self.firstCloudLayer) {
// 云彩的 Y 值
y = self.cloudAmplitude * sin(self.cloudCycle * x + self.cloudOffsetX - 10) + self.cloudPointY + 10;
} else if (cloudLayerName == self.secondCloudLayer) {
y = (self.cloudAmplitude + 15) * sin(self.cloudCycle * x + self.cloudOffsetX ) + self.cloudPointY ;
} else if (cloudLayerName == self.thirdCloudLayer) {
y = (self.cloudAmplitude + 30)* sin(self.cloudCycle * x + self.cloudOffsetX + 20) + self.cloudPointY + 10;
} else if (cloudLayerName == self.fourthCloudLayer) {
y = (self.cloudAmplitude + 20)* sin(self.cloudCycle * x + self.cloudOffsetX - 20) + self.cloudPointY - 10;
} else if (cloudLayerName == self.fifthCloudLayer) {
y = (self.cloudAmplitude + 10)* sin(self.cloudCycle * x + self.cloudOffsetX - 10) + self.cloudPointY + 2;
}
// 添加一條直線
CGPathAddLineToPoint(path, nil, x, y);
}
// 添加一條直線
CGPathAddLineToPoint(path, nil, self.cloudWidth, self.frame.size.height);
// 添加一條直線
CGPathAddLineToPoint(path, nil, 0, self.frame.size.height);
// 關(guān)閉該path
CGPathCloseSubpath(path);
cloudLayerName.path = path;
// 釋放該path
CGPathRelease(path);
}
-
推薦幾篇和 CADisplayLink 相關(guān)的深度好文!