1

drawRect を使用して、非常に単純な形状 (下の画像では濃い青色) を描画しています。

CGContextDrawPath これを左から右にアニメーション化して、成長させたいと思います。ここでの注意点は、画像の上部に見られるように、灰色の「最大」の背景が必要だということです。

現在、このアニメーションをシミュレートするために、白いビューを重ねてから、そのサイズをアニメーション化して、青が右にアニメーション化されているように見せています。これが機能している間...背景の灰色の形状が常にそこにある必要があります。オーバーレイされた白いビューでは、これは機能しません。

「現在のコード」バージョンを描画するためのコードは次のとおりです。

    let context = UIGraphicsGetCurrentContext()
    CGContextMoveToPoint(context, 0, self.bounds.height - 6)
    CGContextAddLineToPoint(context, self.bounds.width, 0)
    CGContextAddLineToPoint(context, self.bounds.width, self.bounds.height)
    CGContextAddLineToPoint(context, 0, self.bounds.height)
    CGContextSetFillColorWithColor(context,UIColor(red: 37/255, green: 88/255, blue: 120/255, alpha: 1.0).CGColor)
    CGContextDrawPath(context, CGPathDrawingMode.Fill)

グラフの灰色の「最大」部分を常に表示したまま、青い部分を左から右にアニメーション化するにはどうすればよいですか?

4

2 に答える 2

1

drawRect は静止画像を生成しています。あなたが言っているアニメーションを取得するには、次のことをお勧めします。

  1. CoreAnimation を使用してアニメーションを作成する
  2. UIBezierPath を使用して、必要な形状を作成します
  3. CALayer のマスクを使用して、必要な形状内でアニメーション化します

Playground のコード例を次に示します。

import UIKit
import QuartzCore
import XCPlayground

let view = UIView(frame: CGRect(x: 0, y: 0, width: 120, height: 40))
XCPlaygroundPage.currentPage.liveView = view

let maskPath = UIBezierPath()

maskPath.moveToPoint(CGPoint(x: 10, y: 30))
maskPath.addLineToPoint(CGPoint(x: 10, y: 25))
maskPath.addLineToPoint(CGPoint(x: 100, y: 10))
maskPath.addLineToPoint(CGPoint(x: 100, y: 30))
maskPath.closePath()

let maskLayer = CAShapeLayer()
maskLayer.path = maskPath.CGPath
maskLayer.fillColor = UIColor.whiteColor().CGColor

let rectToAnimateFrom = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 97, height: 40))
let rectToAnimateTo = UIBezierPath(rect: CGRect(x: 0, y: 0, width: 0, height: 40))

let layerOne = CAShapeLayer()
layerOne.path = maskPath.CGPath
layerOne.fillColor = UIColor.grayColor().CGColor

let layerTwo = CAShapeLayer()
layerTwo.mask = maskLayer
layerTwo.fillColor = UIColor.greenColor().CGColor

view.layer.addSublayer(layerOne)
view.layer.addSublayer(layerTwo)

let animation = CABasicAnimation(keyPath: "path")
animation.fromValue = rectToAnimateFrom.CGPath
animation.toValue = rectToAnimateTo.CGPath
animation.duration = 1
animation.repeatCount = 1000
animation.autoreverses = true

layerTwo.addAnimation(animation, forKey: "Nice animation")
于 2016-09-12T17:08:35.720 に答える