2017-09-10 25 views
0

UIViewのカスタムを作成しています。draw(rect:)の方法は、UIBezierPathを使用して大きな幅の円を描くことで、上に四角形を描画します(図のように、ドン色や大きさを考慮しない)。次に、 "設定"アイコン(図2、外側のリングのみを考慮)と一致するように、四角形の回転コピーを作成します。その最後のことを行うには、CGAffineTransform(rotationAngle:)を使って正方形を回転させる必要がありますが、この回転の中心が円の中心ではなくフレームの原点であるという問題があります。ビュー内の特定のポイントを中心に回転を作成するにはどうすればよいですか?UIBezierPath UIViewの中心を中心に回転

picture 1

picture 2

答えて

2

の変換を適用するの起源、ここに円の中心の周りに歯車の歯を回転させるためにCGAffineTransformを使用する歯車の図があります:

class Gear: UIView { 
    var lineWidth: CGFloat = 16 
    let boxWidth: CGFloat = 20 
    let toothAngle: CGFloat = 45 

    override func draw(_ rect: CGRect) { 

     let radius = (min(bounds.width, bounds.height) - lineWidth)/4.0 

     var path = UIBezierPath() 
     path.lineWidth = lineWidth 
     UIColor.white.set() 

     // Draw circle 
     path.move(to: CGPoint(x: center.x + radius, y: center.y)) 
     path.addArc(withCenter: CGPoint(x: center.x, y: center.y), radius: radius, startAngle: 0, endAngle: 2 * .pi, clockwise: true) 
     path.stroke() 

     // Box for gear tooth 
     path = UIBezierPath() 
     let point = CGPoint(x: center.x - boxWidth/2.0, y: center.y - radius) 
     path.move(to: point) 
     path.addLine(to: CGPoint(x: point.x, y: point.y - boxWidth)) 
     path.addLine(to: CGPoint(x: point.x + boxWidth, y: point.y - boxWidth)) 
     path.addLine(to: CGPoint(x: point.x + boxWidth, y: point.y)) 
     path.close() 
     UIColor.red.set() 

     // Draw a tooth every toothAngle degrees 
     for _ in stride(from: toothAngle, through: 360, by: toothAngle) { 
      // Move origin to center of the circle 
      path.apply(CGAffineTransform(translationX: -center.x, y: -center.y)) 

      // Rotate 
      path.apply(CGAffineTransform(rotationAngle: toothAngle * .pi/180)) 

      // Move origin back to original location 
      path.apply(CGAffineTransform(translationX: center.x, y: center.y)) 

      // Draw the tooth 
      path.fill() 
     } 
    } 
} 

let view = Gear(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) 

ここでは、プレイグラウンドで実行されている:

Demo of gear running in a Playground

2

シフトトランスフォーム、 回転、 シフトが戻っ

はあなたが(アップ投票)@ DuncanCの答えのデモンストレーションとして

関連する問題