我有一个UIBezierPath,当我设置点 x 时我需要得到点 y
谢谢
您将需要在点之间进行插值。要访问这些点,最简单的方法是将它们存储到NSMutableArray
. 创建此数组并添加所有 CGPoints,同时将它们添加到您UIBezierPath
的绘图例程中。如果这是不可能的,请参阅此处了解如何从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);
}
@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
}
}