我正在开发一个Android应用程序,我必须实现一个允许我在活动中绘制不同点的函数。
这是我的代码:
public class MainActivity extends AppCompatActivity {
public Paint paint;
public List<Point> coords;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new DrawingView(this));
paint = new Paint();
coords = new ArrayList();
ImageView iv = new ImageView(getApplicationContext());
iv.setImageResource(R.drawable.car);
iv.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
iv.setLayoutParams(parms);
}
class DrawingView extends SurfaceView {
private final SurfaceHolder surfaceHolder;
private final Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
public DrawingView(Context context) {
super(context);
surfaceHolder = getHolder();
paint.setColor(Color.BLACK);
paint.setStyle(Paint.Style.FILL);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
addpoint(event.getX(), event.getY());
}
return false;
}
public void addpoint(float x, float y){
Point point = new Point();
point.x = Math.round(x);
point.y = Math.round(y);
coords.add(point);
for(int i = 0; i< coords.size(); i++) {
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
canvas.drawCircle(coords.get(i).x, coords.get(i).y, 20, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
}
}
每当我触摸屏幕时,我得到并将坐标保存在列表中,然后我尝试绘制点列表,但屏幕上只剩下一个点,我不明白为什么。
那么我如何在屏幕上绘制不同的点(并保存)?
另一个问题:我如何展示背景图片?
答案 0 :(得分:1)
来自官方Javadocs:
drawColor(int color)填充整个画布&#39;位图(限于 当前剪辑)具有指定的颜色,使用srcover porterduff模式。
所以每次画圆圈时,首先要用白色清除整个画布。所以在平局之后,之前绘制的圆圈被清除。
因此,一个选项是保存背景的当前状态,并始终将其绘制在白色顶部,或者尝试不使用drawColor
答案 1 :(得分:0)
for(int i = 0; i< coords.size(); i++) {
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
canvas.drawCircle(coords.get(i).x, coords.get(i).y, 20, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
应该是
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.WHITE);
for(int i = 0; i< coords.size(); i++) {
canvas.drawCircle(coords.get(i).x, coords.get(i).y, 20, paint);
}
surfaceHolder.unlockCanvasAndPost(canvas);
canvas.drawColor(Color.WHITE);
每次画布所有画布,surfaceHolder.unlockCanvasAndPost(canvas);
仅显示最后添加的画布