我想在我自己的观点(R.id.view)上画画,但这段代码似乎没有任何效果。它根本不允许我画任何东西。
public class MainActivity extends Activity implements OnTouchListener
{
Path mPath;
Canvas canvas;
Paint mPaint;
MaskFilter mEmboss;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
View view=(View)findViewById(R.id.view1);
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(12);
canvas = null;
//view.draw(canvas);
mPath = new Path();
Bitmap mBitmap;
//Paint mBitmapPaint = new Paint(Paint.DITHER_FLAG);
mBitmap = Bitmap.createBitmap(210, 170, Bitmap.Config.ARGB_8888);
canvas = new Canvas(mBitmap);
canvas.drawColor(0xFFAAAAAA);
canvas.drawBitmap(mBitmap, 0, 0, mPaint);
//canvas.drawPaint(mPaint);
view.draw(canvas);
canvas.drawPath(mPath, mPaint);
mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 },
0.4f, 6, 3.5f);
view.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
float x = event.getX();
float y = event.getY();
Log.d("x", String.valueOf(x));
Log.d("y", String.valueOf(y));
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.d("a","down");
touch_start(x, y);
//invalidate();
break;
case MotionEvent.ACTION_MOVE:
touch_move(x, y);
// invalidate();
break;
case MotionEvent.ACTION_UP:
touch_up();
// invalidate();
break;
}
return true;
}
});
// mBlur = new BlurMaskFilter(8, BlurMaskFilter.Blur.NORMAL);
}
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;
private void touch_start(float x, float y) {
mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}
private void touch_move(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX)/2, (y + mY)/2);
mX = x;
mY = y;
}
}
private void touch_up() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
canvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}
}
如何在我自己的视野中使用freehanf手指画?
答案 0 :(得分:7)
最好是你创建了一个扩展视图的类,并将其设置为内容视图,它更具动态性。在触摸事件期间,Action_Move参数也会被调用很多,所以最好注意一下,否则当你想要一条曲线时,你会得到一条直线。
修改强>:
你可以通过改变
来开始onCreate
View view = new MyView();
setContentView(view);
在MyView类的内部,您将拥有一个' Path'对象,每次调用Action_UP,你添加到arrayList的路径,使用view.Invalidate();
,然后类将在你的视图类中调用onDraw方法。所以你就这样覆盖它。
@Override
public void onDraw(Canvas c){
for(Path p: listOfPaths){
c.drawPath(p, paint);}
}
注意:这对于简单的绘图很有用,不要期望用这种方法在平板电脑或手机上绘制mona lisa,因为一旦有很多行你可能会注意到滞后。如果你想变得更复杂和专业。查看view.Invalidate(Rect r)
方法,它不会使整个视图无效,只会使您刚绘制的部分无效