Advertisement
stirante

Untitled

Jul 5th, 2017
101
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 KB | None | 0 0
  1. package com.stirante.mangareader;
  2.  
  3. import android.content.Context;
  4. import android.graphics.Bitmap;
  5. import android.graphics.BitmapFactory;
  6. import android.graphics.Canvas;
  7. import android.os.Handler;
  8. import android.os.Looper;
  9. import android.view.View;
  10.  
  11. /**
  12.  * Created by stirante
  13.  */
  14.  
  15. public class BallView extends View {
  16.  
  17.     Handler mHandler = new Handler(Looper.getMainLooper());
  18.     Runnable mTick = new Runnable() {
  19.         public void run() {
  20.             invalidate();
  21.             mHandler.postDelayed(this, 20); // 20ms == 60fps
  22.         }
  23.     };
  24.     private Bitmap ballImage;
  25.     private float x = 0;
  26.     private float y = 0;
  27.     private int dirX = 1;
  28.     private int dirY = 1;
  29.     private int speed = 8;
  30.     private int width = -1;
  31.     private int height = -1;
  32.  
  33.     public BallView(Context context) {
  34.         super(context);
  35.         ballImage = BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher_round);//tutaj zamien na jakies swoje obrazki
  36.         startAnimation();
  37.     }
  38.  
  39.     void startAnimation() {
  40.         mHandler.removeCallbacks(mTick);
  41.         mHandler.post(mTick);
  42.     }
  43.  
  44.     void stopAnimation() {
  45.         mHandler.removeCallbacks(mTick);
  46.     }
  47.  
  48.     @Override
  49.     protected void onDraw(Canvas canvas) {
  50.         if (width <= 0 && height <= 0) return;
  51.         x += dirX * speed;
  52.         y += dirY * speed;
  53.         if (x >= width - ballImage.getWidth()) dirX = -1;
  54.         if (x < 0) dirX = 1;
  55.         if (y >= height - ballImage.getHeight()) dirY = -1;
  56.         if (y < 0) dirY = 1;
  57.         canvas.drawBitmap(ballImage, x, y, null);
  58.     }
  59.  
  60.     @Override
  61.     protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
  62.         super.onMeasure(widthMeasureSpec, heightMeasureSpec);
  63.         width = getMeasuredWidth();
  64.         height = getMeasuredHeight();
  65.     }
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement