2017-01-17 45 views
0

我的六角形不顯示在imageView的中心,如何解決這個問題?這是我的代碼。Swift 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

既有xy等於0。嘗試使用width屬性來計算轉換。

+0

你可以建議我改變我的代碼。 –

+0

@MianShahbazAkram,我已經告訴你該怎麼做,改變'let transform = CGAffineTransform ...'使用'width'和'height'屬性來代替'x'和'y'。 – Preetygeek