2017-01-17 44 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