开发过程中用不到一元一次方程吗?非也,iOS开发中经常会遇到根据某个ScrollView动态偏移量的值来实时设置一个View的透明度,你敢说你不用一元一次方程你能搞定?
想把一个动画效果做好,经常会遇到实时设置的问题,本人遇到过多次,总结出经验,提供方法来专门计算一元一次方程的K值以及b值,方便开发.
BinaryLinearEquation.h + BinaryLinearEquation.m 提供内联函数以及类方法
// Copyright (c) 2014年 Y.X. All rights reserved. // #import <Foundation/Foundation.h> NS_INLINE CGFloat calculateSlope(CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2) { return (y2 - y1) / (x2 - x1); } NS_INLINE CGFloat calculateConstant(CGFloat x1, CGFloat y1, CGFloat x2, CGFloat y2) { return (y1*(x2 - x1) - x1*(y2 - y1)) / (x2 - x1); } @interface BinaryLinearEquation : NSObject /** * 计算一元一次方程的斜率 K * * Y = kX + b,输入两个点坐标的值(x1, y1), (x2, y2)来计算斜率k的值 * * @param 坐标值 两个点的坐标值(x1, y1), (x2, y2) * @return 计算得出的斜率值 */ + (CGFloat)calculateSlopeWithX1:(CGFloat)x1 Y1:(CGFloat)y1 X2:(CGFloat)x2 Y2:(CGFloat)y2; /** * 计算一元一次方程的常数 b * * Y = kX + b,输入两个点坐标的值(x1, y1), (x2, y2)来计算常数b的值 * * @param 坐标值 两个点的坐标值(x1, y1), (x2, y2) * @return 计算得出的常数值 */ + (CGFloat)calculateConstantWithX1:(CGFloat)x1 Y1:(CGFloat)y1 X2:(CGFloat)x2 Y2:(CGFloat)y2; @end
// Copyright (c) 2014年 Y.X. All rights reserved. // #import "BinaryLinearEquation.h" @implementation BinaryLinearEquation + (CGFloat)calculateSlopeWithX1:(CGFloat)x1 Y1:(CGFloat)y1 X2:(CGFloat)x2 Y2:(CGFloat)y2 { return (y2 - y1) / (x2 - x1); } + (CGFloat)calculateConstantWithX1:(CGFloat)x1 Y1:(CGFloat)y1 X2:(CGFloat)x2 Y2:(CGFloat)y2 { return (y1*(x2 - x1) - x1*(y2 - y1)) / (x2 - x1); } @end
测试:
y = 7x - 9
k = 7
b = -9
两个点(0, -9),(9/7, 0)
---------------------------------------------------------------------------------------------
NSLog(@"%f", calculateSlope(0.f, -9.f, 9.f/7.f,
0.f));
NSLog(@"%f", calculateConstant(0.f, -9.f,
9.f/7.f, 0.f));
NSLog(@"%f",
[BinaryLinearEquation calculateSlopeWithX1:0.f
Y1:-9.f
X2:9.f/7.f Y2:0.f]);
NSLog(@"%f",
[BinaryLinearEquation calculateConstantWithX1:0.f
Y1:-9.f
X2:9.f/7.f Y2:0.f]);
---------------------------------------------------------------------------------------------
2014-03-28 09:46:00.898 woobooWall[1440:60b] 7.000000
2014-03-28
09:46:00.899 woobooWall[1440:60b] -9.000000
2014-03-28 09:46:00.899
woobooWall[1440:60b] 7.000000
2014-03-28 09:46:00.899
woobooWall[1440:60b] -9.000000
使用时请将数据转换为CGFloat型.
附录:
原文:http://www.cnblogs.com/YouXianMing/p/3630012.html