2017-01-17 11 views
0

私の六角形がイメージの中央に表示されませんビュー、これを修正する方法?ここに私のコードです。スウィフト3:六角形がイメージの中心を表示していません。

func roundedPolygonPath(rect: CGRect, lineWidth: CGFloat, sides: NSInteger, cornerRadius: CGFloat, rotationOffset: CGFloat = 0) 
     -> UIBezierPath { 
     let path = UIBezierPath() 
     let theta: CGFloat = CGFloat(2.0 * M_PI)/CGFloat(sides) // How much to turn at every corner 
     // let offset: CGFloat = cornerRadius * tan(theta/2.0)  // Offset from which to start rounding corners 
     let width = min(rect.size.width, rect.size.height)  // Width of the square 

     let center = CGPoint(x: rect.origin.x + width + 10/2.0, y: rect.origin.y + width/2.0) 

     // Radius of the circle that encircles the polygon 
     // Notice that the radius is adjusted for the corners, that way the largest outer 
     // dimension of the resulting shape is always exactly the width - linewidth 
     let radius = (width - lineWidth + cornerRadius - (cos(theta) * cornerRadius))/2.0 

     // Start drawing at a point, which by default is at the right hand edge 
     // but can be offset 
     var angle = CGFloat(rotationOffset) 

     let corner = CGPoint(center.x + (radius - cornerRadius) * cos(angle), center.y + (radius - cornerRadius) * sin(angle)) 
     path.move(to: CGPoint(corner.x + cornerRadius * cos(angle + theta), corner.y + cornerRadius * sin(angle + theta))) 

     for _ in 0 ..< sides { 
      angle += theta 

      let corner = CGPoint(center.x + (radius - cornerRadius) * cos(angle), center.y + (radius - cornerRadius) * sin(angle)) 
      let tip = CGPoint(center.x + radius * cos(angle), center.y + radius * sin(angle)) 
      let start = CGPoint(corner.x + cornerRadius * cos(angle - theta), corner.y + cornerRadius * sin(angle - theta)) 
      let end = CGPoint(corner.x + cornerRadius * cos(angle + theta), corner.y + cornerRadius * sin(angle + theta)) 

      path.addLine(to: start) 
      path.addQuadCurve(to: end, controlPoint: tip) 
     } 

     path.close() 

     // Move the path to the correct origins 
     let bounds = path.bounds 
     let transform = CGAffineTransform(translationX: -bounds.origin.x + rect.origin.x + lineWidth/2.0, 
              y: -bounds.origin.y + rect.origin.y + lineWidth/2.0) 
     path.apply(transform) 

     return path 
} 

enter image description here

+0

正六角形の幅と高さが等しくない。 'height = a; width = a * sqrt(3)/ 2; 'あなたの場合、したがって、ポイントを 'a *(1 - (sqrt(3)/ 2))/ 2'か何かで翻訳する必要があります。 – holex

+0

私のコードで何をしているのか教えていただけますか? –

+0

あなたはあなたのビュー内の所望の位置にあなたの六角形を揃えるすべての「x」座標にオフセットを適用する必要があります。 – holex

答えて

0

この要素の両方がxを有し、y0に等しいです。変換を計算するには、widthプロパティを使用してみます。

+0

私のコードを変更してもらえますか? –

+0

@MianShahbazAkram、私はすでにあなたに何をすべきかを教えました。 'let transform = CGAffineTransform ...'を 'x'と' y'の代わりに 'width'と' height'プロパティを使うように変更しました。 – Preetygeek

関連する問題