gpt4 book ai didi

java - Android中如何用canvas绘制不同的点

转载 作者:行者123 更新时间:2023-12-01 09:21:14 26 4
gpt4 key购买 nike

我正在开发一个 Android 应用程序,我必须实现一个功能,允许我在 Activity 中绘制不同的点。

这是我的代码:

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);
}
}
}
}

每次我触摸屏幕时,我都会得到坐标并将其保存在列表中,然后我尝试绘制点列表,但屏幕上只剩下一个点,我不明白为什么。

那么我如何在屏幕上绘制不同的点(并保存它)?

另一个问题:如何显示背景图像?

最佳答案

来自官方 Javadocs:

drawColor(int color) Fill the entire canvas' bitmap (restricted to the current clip) with the specified color, using srcover porterduff mode.

所以每次你画一个圆圈时,首先要用白色清除整个 Canvas 。所以画完之后,之前画的圆就被清除了。

因此,一种选择是保存背景的当前状态,并始终将其绘制在白色之上,或者尝试不使用drawColor

关于java - Android中如何用canvas绘制不同的点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40153975/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com