package com.example.zidingyi;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View {
float paintX =400;
float paintY =600;
public DrawView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
/**
* 这个方法会在初始化后背调用一次,invaildate()的时候会被调用
*/
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint=new Paint();//设置一个笔
paint.setAntiAlias(true);//设置没有锯齿
paint.setColor(Color.RED);//设置笔的颜色
canvas.drawCircle(paintX, paintY, 50, paint);//距离画圆
}
}
package com.example.zidingyi;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.LinearLayout;
import android.widget.Toast;
public class MainActivity extends Activity {
private LinearLayout layout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
layout = (LinearLayout) findViewById(R.id.layout);//找到这个空间
final DrawView drawView = new DrawView(this);//创建自定义的控件
drawView.setMinimumHeight(300);
drawView.setMinimumWidth(500);
layout.addView(drawView);//讲自定义的控件进行添加
//设置一个触摸事件
drawView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
//改变之前的X,Y
drawView.paintX=event.getX();
drawView.paintY=event.getY();
//调用重新绘制
drawView.invalidate();
return true;
}
});
}
}