建立一個簡單的android塗鴉工程

        爲了測試一些別的算法,建立一個簡單的塗鴉工程。

1. clipse建立一個android工程



           按提示生成android工程,會生成一個的android文件,如下:

package com.mystroke;

import android.app.Activity;
import android.os.Bundle;

public class MystrokeActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
         

2. 添加利用view來進行塗鴉的代碼

     在src下new一個class, 類命取爲HandwritingView,生成一個空的類,如下:


             在HandwritingView裏添加代碼如下(代碼來源於http://blog.csdn.net/arui319/article/details/5870651):

package com.mystroke;

import android.content.Context;  
import android.graphics.Canvas;  
import android.graphics.Color;  
import android.graphics.Paint;  
import android.graphics.Path;  
import android.graphics.Paint.Style;  
import android.view.MotionEvent;  
import android.view.View;  
/** 
 * Example for hand writing. 
 *  
 * @author http://blog.csdn.net/arui319 
 * @version 2010/09/07 
 *  
 */  
public class HandwritingView extends View {  
    private Paint paint = null;  
    private Path path = null;  
    public HandwritingView(Context context) {  
        super(context);  
        path = new Path();  
        paint = new Paint();  
        paint.setColor(Color.YELLOW);  
        paint.setStyle(Style.STROKE);  
        paint.setAntiAlias(true);  
        this.setBackgroundColor(Color.BLACK);  
    }  
    @Override  
    public boolean onTouchEvent(MotionEvent event) {  
        if (event.getAction() == MotionEvent.ACTION_DOWN) {  
            int x = (int) event.getX();  
            int y = (int) event.getY();  
            path.moveTo(x, y);  
            invalidate();  
            return true;  
        } else if (event.getAction() == MotionEvent.ACTION_MOVE) {  
            int x = (int) event.getX();  
            int y = (int) event.getY();  
            path.lineTo(x, y);  
            invalidate();  
            return true;  
        }  
        return super.onTouchEvent(event);  
    }  
    @Override  
    protected void onDraw(Canvas canvas) {  
        super.onDraw(canvas);  
        if (path != null) {  
            canvas.drawPath(path, paint);  
        }  
    }  
}  
         修改文件MystrokeActivity.java如下:

package com.mystroke;

import android.app.Activity;
import android.os.Bundle;

public class MystrokeActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        setContentView(new HandwritingView(this));
    }
}
       跑工程,完成。
      



發佈了41 篇原創文章 · 獲贊 2 · 訪問量 14萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章