自定义的View,实现一个跟随手指的小球

/*
 * 开发自定义的View,实现一个跟随手指的小球。当用户通过手指在屏幕上拖动时,程序就监听到这个动作,并把手指动作的位置传入自定义的UI组件中,并通知该组件重绘该图。
 */

import 略

public class Ex02_2Activity extends Activity {
 /** Called when the activity is first created. */
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  // 创建DrawView组件
  final DrawView draw = new DrawView(this);
  // 获取布局文件
  LinearLayout root = (LinearLayout) findViewById(R.id.linearlayout);
  // 设置自定义组件的最大宽度和高度
  draw.setMinimumHeight(500);
  draw.setMinimumWidth(300);
  // 为draw组件绑定Touch事件
  draw.setOnTouchListener(new OnTouchListener() {

   public boolean onTouch(View v, MotionEvent event) {
    // TODO Auto-generated method stub
    // 修改组件中的currentX和currentY的值
    draw.currentX = event.getX();
    draw.currentY = event.getY();
    // 通知draw组件重绘
    draw.invalidate();
    // 返回true表明处理方法已经处理了该事件
    return true;
   }

  });
  // 向布局文件中加入自定义的组件
  root.addView(draw);
 }
}

// 自定义一个View类,继承View
class DrawView extends View {
 public float currentX = 40;
 public float currentY = 50;

 public DrawView(Context context) {// 构造函数
  super(context);
 }

 // 重写View中的onDraw方法
 public void onDraw(Canvas canvas) {
  super.onDraw(canvas);
  // 创建画笔
  Paint p = new Paint();
  // 设置画笔颜色
  p.setColor(Color.RED);
  // 绘制一个小圆
  canvas.drawCircle(currentX, currentY, 15, p);
 }

}
/****************** XML文件代码*************************/
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/linearlayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

</LinearLayout>

/********************************* 源程序完 ***************************/
下面看下这个程序的截图:

总结:程序中最重要的地方是重写了View中的onDraw()方法。

再利用了 canvas.drawCircle(float cx, float cy, float radius, Paint paint)方法绘制了一个圆。

android API对这个方法的参数是这样解释的:

// 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

其实看API中我们还可学到很多方法。。。

程序中的draw.invalidate()也是必须的,它的功能是通知draw组件重图案。

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值