自定义图形类:
package com.example.dell.androidtwo;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
/**
* Created by dell on 2016/8/31.
*/
public class Round extends View {
//定义矩形长宽
private static final int WIDTH = 90;
private Rect rect = new Rect(0, 0, WIDTH, WIDTH);
//画笔
private static Paint paint = new Paint();
//点击位置和图形边界的偏移量
private int deltaX,deltaY;
//代码调用构造
public Round(Context context) {
super(context);
paint.setColor(Color.BLACK);
paint.setAntiAlias(true);
}
//XML调用构造
public Round(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setColor(Color.RED);
paint.setAntiAlias(true);
}
//绘制图形
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawCircle(rect.centerX(),rect.centerY(),WIDTH/2, paint);
}
//触摸移动并优化
@Override
public boolean onTouchEvent(MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if(!rect.contains(x, y)) {
//没有在矩形上点击,不处理触摸消息
return false;
}
deltaX = x - rect.left;
deltaY = y - rect.top;
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_UP:
Rect old = new Rect(rect);
//更新矩形的位置
rect.left = x - deltaX;
rect.top = y - deltaY;
rect.right = rect.left + WIDTH;
rect.bottom = rect.top + WIDTH;
old.union(rect);//要刷新的区域,求新矩形区域与旧矩形区域的并集
invalidate(old);//出于效率考虑,设定脏区域,只进行局部刷新,不是刷新整个view
break;
}
return true;//处理了触摸消息,消息不再传递
}
}
主类:
package com.example.dell.androidtwo;
import android.content.res.Resources;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class Hello extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//XML调用
setContentView(R.layout.activity_hello);
//代码调用
/* Round round = new Round(this);
setContentView(round);*/
}
}
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"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.example.dell.androidtwo.Hello">
<com.example.dell.androidtwo.Round
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>