Himi原创,转载务必注明出处!
原文地址:http://blog.csdn.net/xiaominghimi/archive/2011/06/20/6555828.aspx
首先对于《赛贝尔曲线》不是很了解的童鞋,请自觉白度百科、google等等...
为了方便偷懒的童鞋,这里给个《贝赛尔曲线》百科地址,以及一段话简述《贝赛尔曲线》:
《贝赛尔曲线》白度百科快速地址:http://baike.baidu.com/view/4019466.htm
贝塞尔曲线又称贝兹曲线或贝济埃曲线,一般的矢量图形软件通过它来精确画出曲线,贝兹曲线由线段与节点组成,节点是可拖动的支点,线段像可伸缩的皮筋;
上面这一段话其实就“线段像可伸缩的皮筋”这一句比较重要,也很容易理解;
至于贝赛尔曲线的实现,在Android中极其的简单,因为它是Android封装的一个方法,这个能不简单么。。。。。。只不过它隐藏的比较深,它隐藏于Path类中,方法如下:
android.graphics.Path.quadTo(float x1, float y1, float x2, float y2)
Since: API Level 1
此方参数解释:
第一个参数:操作点的x坐标
第二个参数:操作点的y坐标
第三个参数:结束点的x坐标
第四个参数:结束点的y坐标
从API中看出,赛贝尔曲线从API-1就开始支持了;
public class Bezier extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(new BezierView(this));
}
private class BezierView extends SurfaceView implements Callback,Runnable{
private int mStartX;
private int mStartY;
private int mControlX;
private int mControlY;
private int mEndX;
private int mEndY;
private Random mRandom;
private Path mPath;
private Paint mPaint;
private boolean mIsFlag=false;
private int mScreenWidth;
private int mScreenHeight;
private SurfaceHolder mSurfaceHolder;
private Canvas mCanvas;
private Thread mThread;
public BezierView(Context context) {
super(context);
mSurfaceHolder=this.getHolder();
mSurfaceHolder.addCallback(this);
mPath=new Path();
mPaint=new Paint();
mPaint.setAntiAlias(true);
mPaint.setStyle(Style.STROKE);
mPaint.setStrokeWidth(5);
mPaint.setColor(Color.WHITE);
mRandom=new Random();
setFocusableInTouchMode(true);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mScreenWidth=getWidth();
mScreenHeight=getHeight();
mIsFlag=true;
mThread=new Thread(this);
mThread.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mIsFlag=false;
}
@Override
public void run() {
while(mIsFlag){
doDraw();
doLogic();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
private void doLogic() {
if (mEndX!=0&&mEndY!=0) {
mControlX=mRandom.nextInt((mEndX-mStartX)/2);
mControlY=mRandom.nextInt((mEndY-mStartY)/2);
}
}
private void doDraw() {
try {
mCanvas=mSurfaceHolder.lockCanvas();
if (mCanvas!=null) {
mCanvas.drawColor(Color.BLACK);
drawPath();
}
} catch (Exception e) {
// TODO: handle exception
}finally{
if (mCanvas!=null) {
mSurfaceHolder.unlockCanvasAndPost(mCanvas);
}
}
}
private void drawPath() {
mPath.reset();
mPath.moveTo(mStartX, mStartY);
mPath.quadTo(mControlX, mControlY, mEndX, mEndY);
mCanvas.drawPath(mPath, mPaint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mEndX=(int)event.getX();
mEndY=(int)event.getY();
return true;
}
}
}