0

我的代码中的位图图像(微笑)在屏幕上随机移动。每当用户单击随机移动的位图图像时,我想显示一条消息。我尝试使用 Ontouch() 方法,但找不到解决方案。

公共类 MainActivity 扩展 Activity {

Myclass ourView;
Bitmap smile;
TextView dis;
int x=0,y=0,a=0,b=0;


 @Override
protected void onCreate(Bundle savedInstanceState) {
     requestWindowFeature(Window.FEATURE_NO_TITLE);
     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

    super.onCreate(savedInstanceState);
    ourView=new Myclass(this);
    setContentView(ourView);



}

 public class Myclass extends View implements OnTouchListener{


        int changingX=0,changingY=0;
        Random crazy = new Random();
        Paint ourblue=new Paint();
        Paint Text=new Paint();
        Paint text=new Paint();


        public Myclass(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
            smile=BitmapFactory.decodeResource(getResources(), R.drawable.smiling);

        }



        @Override
        protected void onDraw(Canvas canvas) {
            // TODO Auto-generated method stub
            super.onDraw(canvas);

            ourblue.setARGB(220, 221, 243, 249);
            canvas.drawPaint(ourblue);
             a=crazy.nextInt(350);
             b=crazy.nextInt(550);
            canvas.drawBitmap(smile,a,b , null);


            if(x>(a-20)&&x<(a+20)&&y>(b-20)&&y<(b+20))
            {

                text.setARGB(220, 0, 0, 0);
                text.setTextAlign(Align.CENTER);
                text.setTextSize(50);
                canvas.drawText("Awesome", 100, 100, text);
            }



            for(int i=0;i<1000000;i++)
            {
            }
            invalidate();




        }

        public boolean onTouch(View arg0, MotionEvent event) {
            // TODO Auto-generated method stub
            x=(int) event.getX();
             y=(int) event.getY();
            return true;


        }

 }

}

4

1 回答 1

0
  1. Keep track of your Bitmap's rectangle as it moves randomly
  2. Create a class-wide flag: boolean displayText
  3. In your onTouch method, always check if the touch occurs inside your Bitmap's rectangle. If it does, then set displayText = true else set it to false
  4. In your onDraw method, check if displayText is true, if so draw the text. If not, don't draw it.
于 2013-09-13T17:15:13.413 回答