简体   繁体   中英

UIImage at last point of UIBezierPath

I want to add a UIImage at last point of UIBezierPath like the image bellow:

Circle Path

Code:

let consume = 0.25
let x = self.frame.size.width / 2.0
let y = self.frame.size.height / 2.0
let radius = (frame.size.width - 10) / 2.0
let startAngle: CGFloat = CGFloat(M_PI * (-1/2))
let endAngle = CGFloat(M_PI * 2 - M_PI/2 * consume)
let circlePath = UIBezierPath(arcCenter: CGPoint(x: x, y: y), radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)

circleLayer = CAShapeLayer()
circleLayer.path = circlePath.cgPath
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.strokeColor = UIColor.red.cgColor
circleLayer.lineWidth = 8.0;

let image = UIImage(named: "myCoolImage")
let imageView = UIImageView(image: image)
// coordX and coordY must be at last point of UIBezierPath
imageView.frame = CGRect(x: coordX, y: coordY, width: 20.0, height: 20.0)
self.addSubview(imageView)

I've tried the following:

let coordX: CGFloat = cos(endAngle) * radius
let coordY: CGFloat = sin(endAngle) * radius

Result: Positive coordX and coordY

The main problem is how to calculate the coordX and coordY.

For the sake of having an actual, fully fleshed out answer, here's basically what you need.

let consume = 0.25
let x = self.frame.size.width / 2.0
let y = self.frame.size.height / 2.0
let radius = (frame.size.width - 10) / 2.0
let startAngle: CGFloat = CGFloat(M_PI * (-1/2))
let endAngle = CGFloat(M_PI * 2 - M_PI/2 * consume)
let circlePath = UIBezierPath(arcCenter: CGPoint(x: x, y: y), radius: radius, startAngle: startAngle, endAngle: endAngle, clockwise: false)

circleLayer = CAShapeLayer()
circleLayer.path = circlePath.cgPath
circleLayer.fillColor = UIColor.clear.cgColor
circleLayer.strokeColor = UIColor.red.cgColor
circleLayer.lineWidth = 8.0;

let imageSize = 20.0
// Center + cos/sin(angle) * radius, then subtract half
// the image size so it will be centered on the line
let coordX: CGFloat = x + (cos(endAngle) * radius) - (imageSize / 2.0)
let coordY: CGFloat = y - (sin(endAngle) * radius) - (imageSize / 2.0)

let image = UIImage(named: "myCoolImage")
let imageView = UIImageView(image: image)
// coordX and coordY must be at last point of UIBezierPath
imageView.frame = CGRect(x: coordX, y: coordY, width: imageSize, height: imageSize)
self.addSubview(imageView)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM