0

在我的触摸事件应用程序中,我想绘制矩形 - 我尝试了这个。但没有确切地知道如何绘制。请帮助我。我想在触摸的点上绘制矩形。如何在 drawRect() 方法中使用 getX() 和 getY()?下面是代码-

public boolean onTouch(View v, MotionEvent event) {
             if(event.getAction()==MotionEvent.ACTION_DOWN) {
                                int X=event.getX(); int Y=event.getY();
                    Paint paint = new Paint();
                    paint.setAntiAlias(true);
                    paint.setColor(getResources().getColor(R.color.Yellow)) ;
                    paint.setAlpha(opacity);
                               Canvas canvas1 = new Canvas(mutableimage1);
                          canvas1.drawRect(2.5f,2.5f,2.5f,2.5f, paint);
                                 }
              }
4

1 回答 1

0

Don't instantiate a new object in the onTouch method : canvas1 = new Canvas(...) It will cause freezes and lags. Create this canvas once for good at the creation of your view.

Be carefull I think your drawRect() call won't draw what you need : you are drawing a rect with x=2.5 y = 2.5 width=2.5 height=2.5

I assume you need to position your rect according to the touch position :

//set the x and y pos according to the touch point
// by removing half the size of the rect we center it on this point ;)
canvas1.drawRect( X-1.25f, Y-1.25f, 2.5F, 2.5f, paint );

Otherwise that's quite correct, but be aware that you are drawing on a mutable bitmap ("mutableimage1") that won't necessary be displayed.

You probably want to add the display in the onDraw(Canvas viewCanvas) method of your view. using :

viewCanvas.drawBitmap(mutableimage1, 0,0, aPreviouslyCreatedPaint);

于 2013-03-03T13:54:27.580 回答