自定义view
跟随当前点击位置
package com.view; 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 Ontuch extends View { // 自定义X轴 public float X; // 自定义Y轴 public float Y; public Ontuch(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); Paint paint = new Paint(); paint.setTextSize(20); canvas.drawColor(Color.BLUE); // 设置园的X轴和Y轴用你点击到的位置 canvas.drawCircle(X, Y, 20, paint); } @Override public boolean onTouchEvent(MotionEvent event) { // TODO Auto-generated method stub this.Y = event.getY();// 获取X轴的位置 this.X = event.getX();// 获取Y轴的位置 this.invalidate();// 重绘当前对象 return true; } }
画图形
package com.view; import android.R.color; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.provider.CalendarContract.Colors; import android.util.AttributeSet; import android.view.View; public class CustomTitleView extends View { public CustomTitleView(Context context) { super(context); // TODO Auto-generated constructor stub } public CustomTitleView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub } public CustomTitleView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // TODO Auto-generated constructor stub } @Override protected void onDraw(Canvas canvas) { // TODO Auto-generated method stub super.onDraw(canvas); Paint p = new Paint();// 自定义画笔 p.setColor(Color.BLUE);// 画笔的颜色 p.setTextSize(30);// 画板中文字的大小 p.setStrokeWidth(20);// 画板中线的宽度 canvas.drawColor(Color.GREEN);// 画板的颜色 canvas.drawLine(30, 50, 50, 500, p);// 画板中线的位置 canvas.drawText("画板文字", 100, 100, p);// 画板文字 和文字所在的位置 // 园所在的位置 第一个是距离左边多少 第二个是距离上边多少 第三个是园的大小 canvas.drawCircle(10, 10, 50, p); } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { // TODO Auto-generated method stub // super.onMeasure(widthMeasureSpec, heightMeasureSpec); setMeasuredDimension(256, 358);// 画板的宽和高 } }
布局用法
<LinearLayout 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" android:orientation="vertical" tools:context=".MainActivity" > <com.view.CustomTitleView android:layout_width="300dp" android:layout_height="200dp" android:text="123" > </com.view.CustomTitleView> <com.view.Ontuch android:layout_width="match_parent" android:layout_height="match_parent" > </com.view.Ontuch> </LinearLayout>