我在主要活动中创建了一个名为DrawView
的自定义视图。我在onDraw()
类中实现了DrawView
方法,它最初绘制了一个圆圈。然后我添加了一个触摸监听器,这样当用户点击时,它就会绘制一个正方形。我到达了用户点击的部分并绘制了一个正方形。我不确定该怎么做。
public class TestActivity extends Activity {
DrawView drawing;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup myLayout = (ViewGroup) findViewById(R.id.mainLayout);
drawing = new DrawView(this);
myLayout.addView(drawing);
drawing.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
// draw a square
}
return true;
}
});
}
private class DrawView extends View {
public DrawView(Context context) {
super(context);
}
protected void onDraw(Canvas canvas) {
Paint myPaint = new Paint();
myPaint.setColor(Color.BLACK);
// draw a circle
}
}
}
非常感谢帮助。
答案 0 :(得分:2)
这里是用户向下,触摸侦听器触发时移动和向上绘制矩形的简单片段,只是在DrawView类中覆盖而不是通过setOnTouchListener()
在DrawView类中定义Rect r = new Rect()然后在DrawView类中实现此代码
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
sx = event.getX();
sy = event.getY();
r.set(sx,sy,sx,sy);
}else if(event.getAction==MotionEvent.ACTION_UP){
r.set(sx,sy,event.getX(),event.getY());
}else if(event.getAction==MotionEvent.ACTION_MOVE){
r.set(sx,sy,event.getX(),event.getY());
}
invalidate();
return true;
}
这是onDraw()
public void onDraw(Canvas canvas){
super.onDraw(canvas);
canvas.drawRect(r, new Paint());
}
答案 1 :(得分:1)
您可以创建一个绘图监听器:
public interface OnDrawListener {
void onDraw(Canvas c);
}
...
private class DrawView extends View {
private OnDrawListener onDrawListener;
public void setOnDrawListener(OnDrawListener onDrawListener) {
this.onDrawListener=onDrawListener;
}
@Override
protected void onDraw(Canvas c) {
onDrawListener.onDraw(c);
}
}
然后编辑覆盖侦听器:
// onCreate
drawing.setOnDrawListener(new OnDrawListener() {
@Override
public void onDraw(Canvas c) {
// draw circle
}
});
然后再次触摸事件并覆盖它以绘制正方形。
答案 2 :(得分:0)
你必须覆盖原始的类函数:
@Override
public void onDraw(Canvas canvas
要强制绘图,请使用viewObject.invalidate()
答案 3 :(得分:0)
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(Color.GREEN);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(5);
protected void onDraw(Canvas canvas) {
canvas.drawColor(Color.TRANSPARENT);
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
canvas.drawPath(mPath, mPaint);
}