我有一个UIBezierPath,当我设置点x
时,我需要得到点y谢谢
答案 0 :(得分:3)
您需要在点之间进行插值。要访问这些点,最简单的方法是将它们存储到NSMutableArray
中。创建此数组并添加所有CGPoints,同时将它们添加到绘图例程中的UIBezierPath
。如果无法做到这一点,请参阅here,了解如何从UIBezierPath
中提取点数。请参阅下面的代码,了解如何实现您的目标:
-(float)getYValueFromArray:(NSArray*)a atXValue:(float)x
{
NSValue *v1, *v2;
float x1, x2, y1, y2;
// iterate through all points
for(int i=0; i<([a count]-1); i++)
{
// get current and next point
v1 = [a objectAtIndex:i];
v2 = [a objectAtIndex:i+1];
// return if value matches v1.x or v2.x
if(x==[v1 CGPointValue].x) return [v1 CGPointValue].y;
if(x==[v2 CGPointValue].x) return [v2 CGPointValue].y;
// if x is between v1.x and v2.x calculate interpolated value
if((x>[v1 CGPointValue].x) && (x<[v2 CGPointValue].x))
{
x1 = [v1 CGPointValue].x;
x2 = [v2 CGPointValue].x;
y1 = [v1 CGPointValue].y;
y2 = [v2 CGPointValue].y;
return (x-x1)/(x2-x1)*(y2-y1) + y1;
}
}
// should never reach this point
return -1;
}
-(void)test
{
NSMutableArray *a = [[NSMutableArray alloc] init];
[a addObject:[NSValue valueWithCGPoint:CGPointMake( 0, 10)]];
[a addObject:[NSValue valueWithCGPoint:CGPointMake(10, 5)]];
[a addObject:[NSValue valueWithCGPoint:CGPointMake(15, 20)]];
[a addObject:[NSValue valueWithCGPoint:CGPointMake(20, 30)]];
[a addObject:[NSValue valueWithCGPoint:CGPointMake(35, 50)]];
[a addObject:[NSValue valueWithCGPoint:CGPointMake(50, 0)]];
float y = [self getYValueFromArray:a atXValue:22.5];
NSLog(@"Y value at X=22.5 is %.2f", y);
}
答案 1 :(得分:1)
@ nullp01nter感谢您的回答。正是我需要的! :) 这是我的Swift版本作为PointXYs的数组扩展:
protocol PointXY {
var x : CGFloat { get set }
var y : CGFloat { get set }
}
extension CGPoint: PointXY { }
extension Array where Element: PointXY {
func getYValue(forX x: CGFloat) -> CGFloat? {
for index in 0..<(self.count - 1) {
let p1 = self[index]
let p2 = self[index + 1]
// return p.y if a p.x matches x
if x == p1.x { return p1.y }
if x == p2.x { return p2.y }
// if x is between p1.x and p2.x calculate interpolated value
if x > p1.x && x < p2.x {
let x1 = p1.x
let x2 = p2.x
let y1 = p1.y
let y2 = p2.y
return (x - x1) / (x2 - x1) * (y2 - y1) + y1
}
}
return nil
}
}