我有一个CGRect,我使用翻译和旋转功能旋转,如下所示: -
let ctx: CGContext = UIGraphicsGetCurrentContext()!
ctx.saveGState()
let halfWidth = (selectedCropRect?.size.width)! / 2.0
let halfHeight = (selectedCropRect?.size.height)! / 2.0
let center = CGPoint(x: (selectedCropRect?.origin.x)! + halfWidth, y: (selectedCropRect?.origin.y)! + halfHeight)
// Move to the center of the rectangle:
ctx.translateBy(x: center.x, y: center.y)
// Rotate:
ctx.rotate(by: rotationAngle!);
// Draw the rectangle centered about the center:
let rect = CGRect(x: -halfWidth, y: -halfHeight, width: (selectedCropRect?.size.width)!, height: (selectedCropRect?.size.height)!)
let path = UIBezierPath(rect: rect).cgPath
ctx.addPath(path)
ctx.restoreGState()
现在问题是我需要获得旋转矩形的所有角点并在角点上放置圆形视图,以便用户可以拖动角点并增加/减小rect的大小。知道如何将圆形视图放在旋转矩形的4个角点上吗?
答案 0 :(得分:0)
未经测试,但这有助于指明您正确的方向
guard let rect = selectedCropRect else {
return
}
let rectCenter = CGPoint(x: rect.width/2, y: rect.height/2)
// Or whatever angle you supply
let rotAngle = CGFloat.pi/4.0
// Rotate around center of rect
/*
Instead of creating a new transform you should store a transform
inside of the object you are transforming like UIView does
*/
var transform = CGAffineTransform(translationX: rectCenter.x, y: rectCenter.y)
transform = transform.rotated(by: rotAngle)
transform = transform.translatedBy(x: -rectCenter.x, y: -rectCenter.y)
// Get transformed center
let originalCenter = rectCenter.applying(transform)
var topLeft = originalCenter
topLeft.x -= rectCenter.x
topLeft.y -= rectCenter.y
topLeft = topLeft.applying(transform)
var topRight = originalCenter
topRight.x += rectCenter.x
topRight.y -= rectCenter.y
topRight = topRight.applying(transform)
var botLeft = originalCenter
botLeft.x -= rectCenter.x
botLeft.y += rectCenter.y
botLeft = botLeft.applying(transform)
var botRight = originalCenter
botRight.x += rectCenter.x
botRight.y += rectCenter.y
botRight = botRight.applying(transform)
// Create new path using the orignal supplied rect and transform
let path = CGPath(rect: rect, transform: &transform)
let bez = UIBezierPath(cgPath: path)
// Do whatever you need with the context