跟随手指的小球

1.创建小球

public class DrawView extends View
{
    public float currentX = 40;
    public float currentY = 50;
    public DrawView(Context context)
    {
        super(context);
    }
    @Override
    public void onDraw (Canvas canvas)
    {
        super.onDraw(canvas);
        //创建画笔
        Paint p = new Paint();
        //设置画笔的颜色
        p.setColor(Color.RED);
        //绘制一个小圆(作为小球)
        canvas.drawCircle(currentX , currentY , 15 , p);        
    }
}
canvas.drawCircle(currentX , currentY , 15 , p); 
void android.graphics.Canvas.drawCircle(float cx, float cy, float radius, Paint paint)

Draw the specified circle using the specified paint. If radius is <= 0, then nothing will be drawn. The circle will be filled or framed based on the Style in the paint.

Parameters:
cx The x-coordinate of the center of the cirle to be drawn
cy The y-coordinate of the center of the cirle to be drawn
radius The radius of the cirle to be drawn
paint The paint used to draw the circle
2.将组件添加到布局中
public class CustomView extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        //获取布局文件中的LinearLayout容器
        LinearLayout root = (LinearLayout)findViewById(R.id.root);
        //创建DrawView组件
        final DrawView draw = new DrawView(this);
        //设置自定义组件的最大宽度、高度
        draw.setMinimumWidth(300); 
        draw.setMinimumHeight(500); 
        //为draw组件绑定Touch事件
        draw.setOnTouchListener(new OnTouchListener()
        {
            @Override
            public boolean onTouch(View arg0, MotionEvent event)
            {
                //修改draw组件的currentX、currentY两个属性
                draw.currentX = event.getX();
                draw.currentY = event.getY();
                //通知draw组件重绘
                draw.invalidate();
                //返回true表明处理方法已经处理该事件
                return true;
            }        
        });
        root.addView(draw);
    }
}

 

posted @ 2016-03-26 14:38  沉默的羊癫疯  阅读(132)  评论(0编辑  收藏  举报