拖動球

          在這裏我想說的是在規定的區域用手拖動一個自定義的小球,很簡單,首先定義一個畫小球的類,在裏面重寫ondraw方法,而後在main文件中實例化剛纔的類,以後呢給他一個觸摸事件就會隨你的手指移動了……canvas

         1.先看咱們畫小球的那個類吧!代碼以下:this

              public class DrawView extends View事件

              {get

                  public float currentX=40;it

                  public float currentY=50;io

                  public DrawView (Context context){class

                                 super(context);date

                       }            List

                   protected void onDraw(Canvas canvas){float

                           super.onDraw(canvas);

                           Paint p=new Paint();

                           p.setColor(Color.BULE);

                           canvas.drawCircle(currentX,currentY,15,p);

                      }

               }

          2.定義好圓後咱們來寫main裏面的,仍是看代碼吧!

               public class MainActivity extends Activity{

                  protected void onCreate(){

                  super.onCreate(savedInstanceState);

                  LinearLayout root=(LinearLayout)findViewById(R.id.LinearLayout1);

                  final DrawView draw=new DrawView(this);

                  draw.setMinimumHeight(400);

                  draw.setMinimumWidth(500);

                  draw.setOnTouchListener(new OnTouchListener(){

                               public boolean onTouch(View arg0,MotionEvent arg1){

                              draw.currentX.=arg1.getX();

                               draw.currentY=arg1.getY();

                               //通知draw組件從新繪製

                                draw.invalidate();

                                retrun true;

                               }

                           });

                          root.addView(draw); 

                       }

                 }

相關文章
相關標籤/搜索