我有一个简单的应用程序,当您在屏幕上移动手指时会画一条线。
我想改变它,而不是在手指后面画一个圆圈,直接跟在你触摸的地方下面。当您沿着屏幕移动手指时,圆圈应该跟随。它不应该留下它背后的道路。
圆圈应出现在触摸屏幕时手指所在的位置,并在手指抬起时消失。
MainActivity:
package com.example.dot2;
import android.app.Activity;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SingleTouchEventListener(this, null));
}
}
SingleTouchEventListener:
package com.example.dot2;
import...
public class SingleTouchEventListener extends View {
private Paint paint = new Paint();
private Path path = new Path();
private Paint mPaint;
public SingleTouchEventListener(Context context, AttributeSet attrs) {
super(context, attrs);
paint.setAntiAlias(true);
paint.setStrokeWidth(6f);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, paint);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
float eventX = event.getX();
float eventY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(eventX, eventY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(eventX, eventY);
break;
case MotionEvent.ACTION_UP:
// nothing to do
break;
default:
return false;
}
// Schedules a repaint.
invalidate();
return true;
}
}
谢谢
答案 0 :(得分:1)
我实际上找到的代码完成了我需要的大部分工作并添加了其余的代码......
以下是代码:
public class drawingView extends View implements OnTouchListener{
static int x,y,r=255,g=255,b=255;
final static int radius=30;
Paint paint;
public drawingView(Context context)
{
super(context);
paint=new Paint();
paint.setAntiAlias(true);
paint.setARGB(255, r, g, b);
setFocusable(true);
this.setOnTouchListener(this);
}
public void onDraw(Canvas canvas)
{
paint.setARGB(255, r, g, b);
//drawing the circle
canvas.drawCircle(x,y,radius,paint);
}
public boolean onTouch(View view,MotionEvent event)
{
x=(int)event.getX()-(radius/2); //logic to plot the circle in exact touch place
y=(int)event.getY()-(radius/2);
//System.out.println("X,Y:"+"x"+","+y);
randColor();
invalidate();
if (event.getAction() == MotionEvent.ACTION_UP) {
paint.setARGB(12, r, g, b);
}
return true;
}
public void randColor()
{
//r=(int)(Math.random()*255);
//g=(int)(Math.random()*255);
//b=(int)(Math.random()*255);
r=1;
g=2;
b=3;
//Toast.makeText(c, "r,g,b="+r+","+g+","+b,Toast.LENGTH_SHORT).show();
}
public void dissColor(){
r=255;
g=255;
b=255;
}
}