如何画拼图?

时间:2013-07-15 11:17:13

标签: ios cashapelayer

我想使用CAShapeLayer绘制拼图形状。我知道如何绘制正方形,但我不知道如何绘制半圆(曲线)。

1 个答案:

答案 0 :(得分:0)

我使用swift和playground编写了这个例子。

import UIKit

let width : CGFloat = 400
let height : CGFloat = 400
let margin : CGFloat = 50


let topLeftCorner = CGPoint(x: 0 + margin, y: 0 + margin)
let topMidle = CGPoint(x: width/2.0, y: 0 + margin)
let topRightCorner = CGPoint(x: width - margin, y: 0 + margin)
let rightMidle = CGPoint(x: width - margin, y: height/2.0)
let bottomRightCorner = CGPoint(x: width - margin, y: height - margin)
let bottomMidle = CGPoint(x: width/2.0, y: height - margin)
let bottomLeftCorner = CGPoint(x: 0 + margin, y: height - margin)
let leftMidle = CGPoint(x: 0 + margin, y: height/2.0)


let jigsawPiece = UIView(frame: CGRect(x: 0, y: 0, width: width, height: height))
let path = UIBezierPath()

// Starting point
path.move(to: topLeftCorner)

// Draw top circle
path.addArc(withCenter: topMidle, radius: margin, startAngle: 0, endAngle: CGFloat(M_PI), clockwise: false)

// Draw line to corner
path.addLine(to: topRightCorner)

// Draw right circle
path.addArc(withCenter: rightMidle, radius: margin, startAngle: CGFloat(M_PI/2.0), endAngle: CGFloat(3*M_PI/2.0), clockwise: false)

// Draw line to corner
path.addLine(to: bottomRightCorner)

// Draw bottom cut
path.addArc(withCenter: bottomMidle, radius: margin, startAngle: 0, endAngle: CGFloat(M_PI), clockwise: false)

// Draw line
path.addLine(to: bottomLeftCorner)

// Draw left cut
path.addArc(withCenter: leftMidle, radius: margin, startAngle: CGFloat(M_PI/2.0), endAngle: CGFloat(3*M_PI/2.0), clockwise: false)

// Draw line
path.addLine(to: topLeftCorner)
path.close()

let layer = CAShapeLayer()
layer.path = path.cgPath
layer.fillColor = UIColor.red.cgColor

jigsawPiece.layer .addSublayer(layer)



jigsawPiece

这是输出。如有必要,您可以将其转换为目标c。

enter image description here