最近在學習自定義控件,菜鳥一枚,自己寫的東西大神勿噴,僅作交流
廢話不多說,直接上碼
package com.jingcai.fu.planegame;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by Administrator on 2016/3/11.
*/
public class DrawView extends View {
public float currentX= 40;
public float currentY= 50;
//定義創建畫筆
Paint paint =new Paint();
public DrawView(Context context) {
super(context);
}
public DrawView(Context context,AttributeSet set) {
super(context,set);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//設置畫筆的顏色
paint.setColor(Color.RED);
canvas.drawCircle(currentX,currentY,15,paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//當前組件的currentX,currentY的兩個屬性
this.currentX = event.getX();
this.currentY = event.getY();
//通知該組件重繪
this.invalidate();
//返回true表明方法已經處理事件
return true;
}
}
還有xml佈局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.jingcai.fu.planegame.MainActivity">
<com.jingcai.fu.planegame.DrawView
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
在代碼中不需要做處理 一個跟着手指運動的view就出來了