Android中在屏幕上涂鸦的例子


这个例子,自定义了一个View,可以接受touch动作,然后在屏幕上即时的显示出touch的轨迹,类似于线条的涂鸦。这个例子主要是演示如何将onTouchEvent与draw配合起来使用。在这个基础上,可以做很多有用的程序。

 

(注意invalidate()这个方法。这个比较关键。加入这个方法的调用主要是为了强制View进行重画。)

    package com.arui;  
    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.youkuaiyun.com/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);  
            }  
        }  
    }  

来源:http://blog.youkuaiyun.com/arui319/article/details/5870651
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值