java - 如何在某个位置单击按钮时绘制圆圈?
问题描述
我对Android很陌生,所以如果我遗漏了什么,我会提前道歉,但我的问题是我每次点击屏幕时都试图在某个位置画一个圆圈。
我尝试过记录,它确实返回了一个与我的 if 语句匹配的 int,但没有绘制任何内容。
public boolean onTouchEvent(MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
drawCirc = true;
xTouch = event.getX();
Log.d("keyboard", "xpos" + xTouch);
yTouch = event.getY();
break;
case MotionEvent.ACTION_UP:
drawCirc = false;
}
return true;
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
Paint paint = new Paint();
paint.setColor(Color.RED);
if(drawCirc) {
if (xTouch < 150 && xTouch>0) {
paint.setColor(Color.RED);
canvas.drawCircle(150, 500, 100, paint);
isPlayer1 = false;
invalidate();
}
}
}
解决方案
@Javanator 是对的,你应该做invalidate
触摸监听器。
同时,您可以尝试下面的代码,它在绘制圆圈时添加动画。
Paint paint = new Paint();
{
paint.setColor(Color.RED);
}
// The radius of the circle you want to draw
// 0 by default
private int radius = 0;
// The animator to animate circle drawing
private ObjectAnimator radiusAnimator;
public void setRadius(int newRadius) {
this.radius = newRadius;
this.invalidate();
}
private void showCircle(boolean show) {
ObjectAnimator animator = this.getRadiusAnimator();
if (show) {
animator.start();
} else {
animator.reverse();
}
}
private ObjectAnimator getRadiusAnimator() {
if (this.radiusAnimator == null) {
this.radiusAnimator = ObjectAnimator.ofInt(this, "radius", 0, 100);
}
return this.radiusAnimator;
}
public boolean onTouchEvent(MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
// drawCirc = true;
xTouch = event.getX();
Log.d("keyboard", "xpos" + xTouch);
yTouch = event.getY();
showCircle(true);
break;
case MotionEvent.ACTION_UP:
// drawCirc = false;
showCircle(false);
}
return true;
}
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (xTouch < 150 && xTouch > 0) {
canvas.drawCircle(xTouch, yTouch, radius, paint);
}
/*
if(drawCirc) {
if (xTouch < 150 && xTouch>0) {
paint.setColor(Color.RED);
canvas.drawCircle(150, 500, 100, paint);
isPlayer1 = false;
invalidate();
*/
}
推荐阅读
- r - 关于在 rlang 4.0 中使用 curly-curly '{{ }}' 的问题
- reactjs - 如何修复 React 过滤器搜索栏
- c# - 将文件放入项目目录但不放入项目的 Nuget 包
- php - Laravel - 验证字段输入应该是一组给定值之一的可空字段
- solr - Solr查询数组的最后一个索引
- kubernetes - 如何解决卷挂载的容器中的错误“没有这样的文件或目录”
- python - 禁用日志文件中的异常
- oracle - 关于数据更改的自定义电子邮件通知
- anylogic - 如何动态改变道路的通行能力
- git - Visual Studio:选择一个工作的 git 存储库