我目前正在 android 中试验我的第一个自定义 View ,并尝试通过 onTouchEvent
在 Canvas 上绘制点,但多次尝试后都失败了。 View 确实检测到我的触摸并在触摸时成功打印出 System.out.println 消息,但它仍然没有在 Canvas 上绘制。
经过多次尝试,我得出的结论是:
package com.techdigy.testapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
public class DrawingBoard extends View {
Canvas canvas;
Bitmap bmp;
BitmapDrawable temp;
public DrawingBoard(Context context, AttributeSet attributeSet) {
super(context,attributeSet);
// TODO Auto-generated constructor stub
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
canvas = new Canvas();
}
protected void onDraw(Canvas canvas) {
//draw view
}
public boolean onTouchEvent(MotionEvent event) {
//detect user touch
float touchX = event.getX();
float touchY = event.getY();
Paint paint = new Paint();
System.out.println("test");
this.canvas.drawPoint(touchX, touchY, paint);
temp = new BitmapDrawable(this.bmp);
this.setBackground(this.temp);
invalidate();
return true;
}
}
最佳答案
试试这个...
public class DrawingBoard extends View {
private Bitmap bmp;
private float touchX;
private float touchY;
private Paint paint;
public DrawingBoard(Context context, AttributeSet attributeSet) {
super(context, attributeSet);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.GREEN);
paint.setStyle(Paint.Style.STROKE);
}
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
setBackgroundDrawable(new BitmapDrawable(getResources(), bmp));
}
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawPoint(touchX, touchY, paint);
}
public boolean onTouchEvent(MotionEvent event) {
// detect user touch
touchX = event.getX();
touchY = event.getY();
System.out.println("test");
invalidate();
return true;
}
}
关于java - Android View 不响应绘图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20322575/