情報元
// UIBezierPath for drawing an x-mark in a CAShapeLayer
private func getXMarkPath() -> CGPath {
let path = UIBezierPath()
// the origin of the path needs to be at 0, 0
path.move(to: CGPoint(x: 0, y: 0))
path.addLine(to: CGPoint(x: 50, y: 50))
path.move(to: CGPoint(x: 50, y: 0))
path.addLine(to: CGPoint(x: 0, y: 50))
return path.cgPath
}
// UIBezierPath for drawing a circle in a CAShapeLayer
private func getCircleMarkPath() -> CGPath {
// arcCenter and the radius should match
let path = UIBezierPath(arcCenter: CGPoint(x: 50, y: 50), radius: 50, startAngle: 0, endAngle: CGFloat.pi*2, clockwise: true)
return path.cgPath
}
private func resizePath(frame: CGRect, path: CGPath) -> CGPath {
let boundingBox = path.boundingBox
let boundingBoxAspectRatio = boundingBox.width / boundingBox.height
let viewAspectRatio = frame.width / frame.height
var scaleFactor: CGFloat = 1.0
if (boundingBoxAspectRatio > viewAspectRatio) {
// width is the limiting factor
scaleFactor = frame.width / boundingBox.width
} else {
// height is the limiting factor
scaleFactor = frame.height / boundingBox.height
}
var scaleTransform = CGAffineTransform.identity
scaleTransform = scaleTransform.scaledBy(x: scaleFactor, y: scaleFactor)
// scaleTransform.translatedBy(x: -boundingBox.minX, y: -boundingBox.minY)
// let scaledSize = boundingBox.size.applying(CGAffineTransform (scaleX: scaleFactor, y: scaleFactor))
// let centerOffset = CGSize(width: (frame.width - scaledSize.width ) / scaleFactor * 2.0, height: (frame.height - scaledSize.height) / scaleFactor * 2.0 )
// scaleTransform = scaleTransform.translatedBy(x: centerOffset.width, y: centerOffset.height)
// CGPathCreateCopyByTransformingPath(path, &scaleTransform)
let scaledPath = path.copy(using: &scaleTransform)
return scaledPath!
}
// assign the resized path to the CAShape layer added to the view's default layer
private func layout() {
let newView = UIView()
newView.frame = CGRect(x: 50, y: 50, width: 100, height: 100)
let xMarkPath = getXMarkPath()
let resizedPath = resizePath(frame: newView.frame, path: xMarkPath)
let shapeLayer = CAShapeLayer()
shapeLayer.strokeColor = UIColor.black.cgColor
shapeLayer.lineWidth = 1
shapeLayer.fillColor = UIColor.blue.cgColor
newView.layer.addSublayer(shapeLayer)
shapeLayer.path = resizedPath
}