温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Android怎么通过触摸动态地在屏幕上画矩形效果

发布时间:2022-04-08 15:26:54 来源:亿速云 阅读:176 作者:iii 栏目:大数据

这篇文章主要介绍了Android怎么通过触摸动态地在屏幕上画矩形效果的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Android怎么通过触摸动态地在屏幕上画矩形效果文章都会有所收获,下面我们一起来看看吧。

需求概述:

  在屏幕上用手指画出一个区域,返回所圈的区域坐标。

  技术实现:

  自定义View,设置画笔及对应参数,在onTouchEvent()回调函数里,对触摸事件进行判断。画出矩形图形。

  代码:

  自定义View:

public class GameView extends View {
  //  声明Paint对象
  private Paint mPaint = null;
  private int StrokeWidth = 5;
  private Rect rect = new Rect(0,0,0,0);//手动绘制矩形
  public GameView(Context context){
    super(context);
    //构建对象
    mPaint = new Paint();
    mPaint.setColor(Color.RED);
    //开启线程
    // new Thread(this).start();
  }
  @Override
  protected void onDraw(Canvas canvas) {
    super.onDraw(canvas);
    //设置无锯齿
    mPaint.setAntiAlias(true);
    canvas.drawARGB(50,255,227,0);
    mPaint.setStyle(Paint.Style.STROKE);
    mPaint.setStrokeWidth(StrokeWidth);
    mPaint.setColor(Color.GREEN);
    mPaint.setAlpha(100);
    // 绘制绿色实心矩形
    canvas.drawRect(100, 200, 400, 200 + 400, mPaint);
    mPaint.setColor(Color.RED);
    canvas.drawRect(rect,mPaint);
  }
  @Override
  public boolean onTouchEvent(MotionEvent event) {
    int x = (int)event.getX();
    int y = (int)event.getY();
    switch (event.getAction()){
      case MotionEvent.ACTION_DOWN:
        rect.right+=StrokeWidth;
        rect.bottom+=StrokeWidth;
        invalidate(rect);
        rect.left = x;
        rect.top = y;
        rect.right =rect.left;
        rect.bottom = rect.top;
      case MotionEvent.ACTION_MOVE:
        Rect old =
        new Rect(rect.left,rect.top,rect.right+StrokeWidth,rect.bottom+StrokeWidth);
        rect.right = x;
        rect.bottom = y;
        old.union(x,y);
        invalidate(old);
        break;
      case MotionEvent.ACTION_UP:
        break;
      default:
        break;
    }
    return true;//处理了触摸信息,消息不再传递
  }
}

调用时,只需要在onCreate()函数里,直接添加就可以:

super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    gameView = new GameView(this);
    addContentView(gameView);

根据需要可以在自定义类中,加入返回圈定范围的函数。

ps:需要注意的是,在手指移动的时候,屏幕需要更新矩形时,原理上删除原来矩形,画上新矩形。但是由于空心矩形边厚度的存在,

会出现遗留的情况,此时要减去border厚度,可以解决上述问题。

Rect old = new Rect(rect.left,rect.top,rect.right+StrokeWidth,rect.bottom+StrokeWidth);

 效果图:

Android怎么通过触摸动态地在屏幕上画矩形效果

关于“Android怎么通过触摸动态地在屏幕上画矩形效果”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“Android怎么通过触摸动态地在屏幕上画矩形效果”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI