我的目标是每次触摸屏幕时画一个圆,而如果我想再次触摸,则前一个圆会消失。
现在发生的是以前的圆圈没有消失,因此每次我触摸屏幕时它们都会加起来。 enter image description here
这是我的代码:
科特琳:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var imageBody: ImageView = findViewById(R.id.imageViewBody)
imageBody.isDrawingCacheEnabled = true
imageBody.buildDrawingCache(true)
imageBody.setOnTouchListener(OnTouchListener { v, event ->
if(event != null){
if (event.action == MotionEvent.ACTION_DOWN) {
val bitmap: Bitmap = imageBody.drawingCache
val pixel: Int = bitmap.getPixel(event.getX().toInt(), event.getY().toInt())
coordX = event.getX()
coordY = event.getY()
val Drawable = imageBody.drawable
val ImageBounds = Drawable.bounds
val scaledHeight = ImageBounds.height()
val scaledWidth = ImageBounds.width()
OrigX = coordX / scaledHeight
OrigY = coordY / scaledWidth
when (pixel) {
Color.rgb(241,241,241) -> {
val canvas = Canvas(bitmap)
val paint = Paint()
paint.color = Color.rgb(255,128,0)
canvas.drawCircle(coordX, coordY, 15F, paint) /**DRAW CIRCLE*/
imageBody.setImageBitmap(bitmap)
imageBody.Invalidate()
}
}
}
}
false
})
}
答案 0 :(得分:0)
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new SfView(this));
}
class SfView 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.RED);
paint.setStyle(Style.FILL);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_DOWN) {
if (surfaceHolder.getSurface().isValid()) {
Canvas canvas = surfaceHolder.lockCanvas();
canvas.drawColor(Color.BLACK);
canvas.drawCircle(event.getX(), event.getY(), 50, paint);
surfaceHolder.unlockCanvasAndPost(canvas);
}
}
return false;
}
}
}
答案 1 :(得分:0)
尝试这个。在操作ACTION_UP
中清除imageView的位图。这是示例代码:
首先将位图放在onTouchListener
之外,例如:
private var bitmap: Bitmap? = null
然后您的onTouchListener
将像:
imageBody.setOnTouchListener({ v, event ->
if(event != null){
if (event.action == MotionEvent.ACTION_DOWN) {
bitmap = Bitmap.createBitmap(imageBody.drawingCache)
val pixel: Int = bitmap.getPixel(event.getX().toInt(), event.getY().toInt())
coordX = event.getX()
coordY = event.getY()
val Drawable = imageBody.drawable
val ImageBounds = Drawable.bounds
val scaledHeight = ImageBounds.height()
val scaledWidth = ImageBounds.width()
OrigX = coordX / scaledHeight
OrigY = coordY / scaledWidth
when (pixel) {
Color.rgb(241,241,241) -> {
val canvas = Canvas(bitmap)
val paint = Paint()
paint.color = Color.rgb(255,128,0)
canvas.drawCircle(coordX, coordY, 15F, paint) /**DRAW CIRCLE*/
imageBody.setImageBitmap(bitmap)
imageBody.Invalidate()
}
}
}
if (event.action == MotionEvent.ACTION_UP) {
if (bitmap != null && !bitmap!!.isRecycled) {
bitmap?.recycle()
bitmap = null
}
}
}
true
})