gpt4 book ai didi

android - 如何禁用无效()?

转载 作者:太空狗 更新时间:2023-10-29 15:19:33 26 4
gpt4 key购买 nike

一开始我的程序是这样的:

enter image description here

但是当我在屏幕上移动图片时,程序会变成:

enter image description here

红色图形是在 onDraw 方法中随机生成的。所以我想四处拖动图片并拥有在移动图片时不会失效的静态背景。

这是我的代码:自定义 View : 包 com.graph.base;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.view.View;
import java.util.Random;

public class CustomView extends View
{
Random random=new Random();
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}

public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
}

public CustomView(Context context) {
super(context);
}
public void onDraw (Canvas canvas)
{
super.onDraw(canvas);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
canvas.drawPaint(paint);
Path path=new Path();
path.moveTo(10, 10);
for (float i=0.5f; i<=140; i+=10)
{
path.quadTo(10+i*5, 10+random.nextInt(500), 10+(i+10)*5, 10+random.nextInt(500));
}
paint.setDither(true);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeJoin(Paint.Join.ROUND);
paint.setStrokeCap(Paint.Cap.ROUND);
paint.setStrokeWidth(2);
canvas.drawPath(path, paint);
}

主 Activity

package com.graph.base;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

public class MainActivity extends Activity {
FrameLayout frame;
ImageView image;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
frame=(FrameLayout)findViewById(R.id.frameLayout1);
image=(ImageView)findViewById(R.id.imageView1);
image.setOnTouchListener(new View.OnTouchListener() {

public boolean onTouch(View v, MotionEvent event) {
Log.e("TAG", "Touch happend");
switch (event.getAction())
{
case MotionEvent.ACTION_MOVE:
{
image.setPadding((int)event.getX(), (int)event.getY(), 0, 0);
break;
}

}

return true;
}
});
}

public void invalidateButton_Click (View v)
{
frame.invalidate();
}
}

最佳答案

您正在 Canvas 上随机绘制线条。每次屏幕无效时都会调用此代码。如果你想保持绘图不变,那么将位图设置到 Canvas 中并绘制到位图中。然后在 onDraw() 方法中将位图绘制到 Canvas 上。

// Outside of onDraw()
Bitmap bmDest = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
Canvas mycanvas = new Canvas(bmDest);
// Do your drawing on the canvas outside of the onDraw() method

在 onDraw() 中,您只需执行以下操作:

canvas.drawBitmap(bmDest, x, y, null);

关于android - 如何禁用无效()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9352209/

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