2016-10-17 56 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)