我想在屏幕上绘制矩形,我如何从用户触摸事件中获得绘制矩形的点?我用onTouchEvent和油漆画了一条线,如下所示。像这样,根据用户的需要绘制线条,我想绘制矩形,但是我无法得到这个的值。请帮助
public class SimpleDrawingView extends View {
private final int paintColor = Color.BLACK;
private Paint drawPaint;
private Path path = new Path();
float pointX;
float pointY;
public SimpleDrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
setupPaint();
}
private void setupPaint() {
// Setup paint with color and stroke styles
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(5);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
pointX = event.getX();
pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(pointX, pointY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(pointX, pointY);
break;
default:
return false;
}
// Force a view to draw again
postInvalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path,drawPaint);
}
}
很简单:
Point2D p1 = null;
Point2D p2 = null;
@Override
public boolean onTouchEvent(MotionEvent event) {
pointX = event.getX();
pointY = event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
p1 = new Point2D(pointX, pointY);
return true;
case MotionEvent.ACTION_UP:
p2 = new Point2D(pointX, pointY);
postInvalidate();
break;
default:
return false;
}
return true;
}
@Override
protected void onDraw(Canvas canvas) {
if(p1!=null && p2!=null) {
canvas.drawRect(p1.getX(), p1.getY(), p2.getX(), p2.getY(), drawPaint);
p1=null;
p2=null;
}
}
您也可以这样做
public class SimpleDrawingView extends View {
private final int paintColor = Color.BLACK;
private Paint drawPaint;
float pointX;
float pointY;
float startX;
float startY;
public SimpleDrawingView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setFocusableInTouchMode(true);
setupPaint();
}
private void setupPaint() {
// Setup paint with color and stroke styles
drawPaint = new Paint();
drawPaint.setColor(paintColor);
drawPaint.setAntiAlias(true);
drawPaint.setStrokeWidth(5);
drawPaint.setStyle(Paint.Style.STROKE);
drawPaint.setStrokeJoin(Paint.Join.ROUND);
drawPaint.setStrokeCap(Paint.Cap.ROUND);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
pointX = event.getX();
pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = pointX;
startY = pointY;
return true;
case MotionEvent.ACTION_MOVE:
break;
default:
return false;
}
// Force a view to draw again
postInvalidate();
return true;
}
@Override
protected void onDraw(Canvas canvas) {
canvas.drawRect(startX, startY, pointX, pointY, drawPaint);
}
}