2016-10-17 24 views
0

的最后一点我想在UIBezierPath的最后一个点添加一个UIImage像波纹管的图像:的UIImage在UIBezierPath

Circle Path

代码:

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) 

我已经试过如下:

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

结果: Positive coordX and coordY

主要问题是如何计算coordX和coordY。

+0

在您使用的代码中,出了什么问题?你目前看到什么结果?看起来你缺少的是图像大小的负偏移量(所以,对于图像大小,位置-x,-y)。 – shortstuffsushi

+0

我用当前结果更新了问题。如果我设置了负偏移量,我的图像将不在屏幕上。 –

+0

你没有在这里展示你coordX和coordY在哪里设置给你的结果。但是,请注意,这些值应该基于x和y_,因此它是x/y(中心)+/- cos/sin(角度)。可以显示更新的代码,并设置这些变量,并指出它们应该基于在x/y? – shortstuffsushi

回答

1

为了有一个实际的,完全充实的答案,这里基本上是你需要的。

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)