跟随手指的小球

本文介绍如何在Android应用中创建一个简单的动画小球,并通过触摸事件实时更新小球的位置。通过继承`View`类并覆盖`onDraw`方法绘制小球,然后在`onTouch`事件中响应用户操作,实现小球位置的动态更新。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 drawncy The y-coordinate of the center of the cirle to be drawnradius The radius of the cirle to be drawnpaint The paint used to draw the circle2.将组件添加到布局中
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);
    }
}

 

转载于:https://www.cnblogs.com/crazyzx/articles/5322903.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值