随手画圆
//------------------自定义控件-----------------------------
package com.bwie.test;
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;
public class DrawCircle extends View{
//给圆设置一个默认的位置
float x=40;
float y=50;
//创建画笔
Paint paint=new Paint();
public DrawCircle(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
public DrawCircle(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public DrawCircle(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//设置画笔颜色
paint.setColor(Color.RED);
//画圆
canvas.drawCircle(x, y, 20, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
//获得触摸点的坐标
x=event.getX();
y=event.getY();
//重新绘制
invalidate();
//返回true消耗此事件
return true;
}
}
//-------------------主布局----------------------------------
<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"
>
<com.bwie.test.DrawCircle
android:layout_width="wrap_content"
android:layout_height="wrap_content"></com.bwie.test.DrawCircle>
</RelativeLayout>
//--------------MainActivity--没有做任何处理-----------------------------
package com.bwie.test;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}