Android画一个随意拖动的圆形

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.Typeface;
import android.view.MotionEvent;
import android.view.View;


/**
 * Created by songximing on 15/12/25.
 */
public class DraggableView extends View {
      /* (non-Javadoc)
         * @see android.view.View#onDraw(android.graphics.Canvas)
         */

    protected float currentx = 0;// 拖拽控件的x坐标
    protected float currenty = 0;// 拖拽控件的y坐标
    private int r = 0;//拖拽球的半径
    private boolean state = false;//判断控件是否应该获得焦点
    private Paint paint = null;//画笔
    private Paint paint1 = null;//画笔
    private Paint paintLine = null;//画笔线
    private Paint paintText = null;//画文字
    private static int ALPHA_1 = 50;//画笔的透明度为半透明
    private static int ALPHA_2 = 255;//画笔的透明度不透明
    private float downX = 0f;//判断是否移动了x
    private float downY = 0f;//判断是否移动了y
    private Context context = null;//上下文
    private DraggableView.ViewCallBack callBack = null;//回调

    public DraggableView(Context context, DraggableView.ViewCallBack callBack) {
        super(context);
        this.context = context;
        this.callBack = callBack;
        initPaint();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawView(canvas, 50, 11);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {

        float x = event.getX();//获取点击的横坐标
        float y = event.getY();//获取点击的纵坐标

        //触摸事件的触发
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN://触摸点击动作
                downX = x;
                downY = y;
                if (!isOption(x, y)) {
                    state = false;
                    return false;
                } else {
                    paint.setAlpha(ALPHA_2);
                    paint1.setAlpha(ALPHA_2);//设置画笔为半透明
                    this.invalidate();
                    state = true;
                }
                break;
            case MotionEvent.ACTION_MOVE://触摸移动动作
                if (state) {
                    viewMove(x, y, event);
                    this.invalidate();
                }
                break;
            case MotionEvent.ACTION_UP://触摸离开动作
                paint.setAlpha(ALPHA_1);//设置画笔为半透明
                paint1.setAlpha(ALPHA_1);//设置画笔为半透明
                this.invalidate();
                if (downX == x && downY == y) {
                    callBack.finishActivity(context);
                }
                break;

        }
        return true;
    }

    /**
     * 画控件
     *
     * @param canvas 画板
     * @param with   控件的宽度比例
     * @param heigh  控件的高度比例
     */

    private void drawView(Canvas canvas, int with, int heigh) {

//        if (getWidth() < getHeight()) {
//            r = getWidth() / with;
//        } else {
//            r = getHeight() / heigh;
//        }
        r = with;
        //如果是第一次画,画起始位置
        if (currentx == 0 && currenty == 0) {
            currentx = getWidth() - r;
            currenty = getHeight() - 3 * r;
            paint.setAlpha(ALPHA_1);
            paint1.setAlpha(ALPHA_1);
        }
        //画一个圆形bitmap
        // Bitmap bt1 = BitmapFactory.decodeResource(getResources(), R.mipmap.ww);
        // Bitmap bt2 = zoomImg(bt1, 2 * r, 2 * r);
        // Bitmap bt = toRoundBitmap(bt2);
        // canvas.drawBitmap(bt, currentx - r, currenty - r, paint);
        //可以改为图片资源

        //用画笔画一个圆球(不使用字体)
        canvas.drawCircle(currentx, currenty, r, paint1);
        canvas.drawCircle(currentx, currenty, r - 5, paint);
        int l = r / 4;
        canvas.drawLine(currentx - l, currenty - l, currentx + l, currenty + l, paintLine);
        canvas.drawLine(currentx - l, currenty + l, currentx + l, currenty - l, paintLine);

        //用画笔画一个圆球(使用字体)
        //canvas.drawCircle(currentx, currenty, r, paint1);
        //canvas.drawCircle(currentx, currenty, r-5, paint);
        //float bottom = paintText.getFontMetrics().bottom;
        //float w = paintText.measureText("uF00D");
        //canvas.drawText("uf00d", currentx - w / 2, currenty + 3 * bottom, paintText);
    }

    /**
     * 初试化画笔
     */
    private void initPaint() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setColor(Color.rgb(18, 26, 34));

        paint1 = new Paint();
        paint1.setAntiAlias(true);
        paint1.setColor(Color.WHITE);

        paintLine = new Paint();
        paintLine.setColor(Color.WHITE);
        paintLine.setStrokeWidth(5);
        paintLine.setAntiAlias(true);

        paintText = new Paint();
        paintText = new Paint();
        paintText.setColor(Color.WHITE);
        Typeface tf = Typeface.createFromAsset(context.getAssets(), "fonts/FontAwesome.ttf");
        paintText.setTextSize(50);
        paintText.setTypeface(tf);

    }

    /**
     * 设置滑动的效果
     *
     * @param x     点击的x坐标轴
     * @param y     点击的y坐标轴
     * @param event 控件的事件
     */
    private void viewMove(float x, float y, MotionEvent event) {
        if (x <= r) {
            currentx = r;
        } else if (x >= getWidth() - r) {
            currentx = getWidth() - r;
        } else if (y <= r) {
            currenty = r;
        } else if (y >= getHeight() - r) {
            currenty = getHeight() - r;
        } else {
            currentx = event.getX();
            currenty = event.getY();
        }
    }

    /**
     * 判断是不是在控件可操作的范围之内
     *
     * @param x 点击的x坐标轴
     * @param y 点击的y坐标轴
     */
    private boolean isOption(float x, float y) {
        if (x > currentx - r && x < currentx + r && y < currenty + r & y > currenty - r)
            return true;
        else
            return false;
    }

    /**
     * 回调
     */
    public interface ViewCallBack {
        public void finishActivity(Context context);
    }

    public Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 获得图片的宽高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片   www.2cto.com
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

    /**
     * 转换图片成圆形
     *
     * @param bitmap 传入Bitmap对象
     * @return
     */
    public Bitmap toRoundBitmap(Bitmap bitmap) {
        int width = bitmap.getWidth();
        int height = bitmap.getHeight();
        float roundPx;
        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;
        if (width <= height) {
            roundPx = width / 2;
            top = 0;
            bottom = width;
            left = 0;
            right = width;
            height = width;
            dst_left = 0;
            dst_top = 0;
            dst_right = width;
            dst_bottom = width;
        } else {
            roundPx = height / 2;
            float clip = (width - height) / 2;
            left = clip;
            right = width - clip;
            top = 0;
            bottom = height;
            width = height;
            dst_left = 0;
            dst_top = 0;
            dst_right = height;
            dst_bottom = height;
        }

        Bitmap output = Bitmap.createBitmap(width,
                height, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(output);

        final int color = 0xff424242;
        final Paint paint = new Paint();
        final Rect src = new Rect((int) left, (int) top, (int) right, (int) bottom);
        final Rect dst = new Rect((int) dst_left, (int) dst_top, (int) dst_right, (int) dst_bottom);
        final RectF rectF = new RectF(dst_left, dst_top, dst_right, dst_bottom);

        paint.setAntiAlias(true);

        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);

        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(bitmap, src, dst, paint);
        return output;
    }
}

调用:

 1  2 
 3 import android.content.Context;
 4 import android.content.Intent;
 5 import android.support.v7.app.AppCompatActivity;
 6 import android.os.Bundle;
 7 import android.view.View;
 8 import android.widget.RelativeLayout;
 9 
10 public class MainActivity extends AppCompatActivity {
11 
12     @Override
13     protected void onCreate(Bundle savedInstanceState) {
14         super.onCreate(savedInstanceState);
15         RelativeLayout relativeLayout = new RelativeLayout(this);//(RelativeLayout) findViewById(R.id.rl);
16         DraggableView draggableView  = new DraggableView(this,new DraggableView.ViewCallBack(){
17 
18             @Override
19             public void finishActivity(Context context) {
20                 Intent intent = new Intent(MainActivity.this,SecondActivity.class);
21                 startActivity(intent);
22                 overridePendingTransition(R.anim.slide_in, R.anim.no_anim);
23             }
24         });
25         relativeLayout.addView(draggableView);
26 
27         setContentView(relativeLayout);
28     }
29 }
原文地址:https://www.cnblogs.com/weifengzz/p/5194638.html