Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package viewmotionexample.ballanimation;
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.graphics.Rect;
- import android.graphics.drawable.Drawable;
- import android.util.AttributeSet;
- import android.view.MotionEvent;
- import android.view.View;
- import java.util.ArrayList;
- import java.util.Random;
- /**
- * Created by David Olsen, 2015
- * Public Domain. Use for anything.
- */
- public class CirclesView extends View {
- Random random = new Random();
- ArrayList<BallDrawing> circles = new ArrayList<>();
- Activity activity;
- Paint backgroundPaint = new Paint();
- public CirclesView(Context context) {
- super(context);
- this.activity = (Activity) context;
- init();
- }
- public CirclesView(Context context, AttributeSet attrs) {
- super(context, attrs);
- this.activity = (Activity) context;
- init();
- }
- public CirclesView(Context context, AttributeSet attrs, int defStyleAttr) {
- super(context, attrs, defStyleAttr);
- this.activity = (Activity) context;
- init();
- }
- @Override
- public boolean onTouchEvent(MotionEvent event) {
- int action = event.getAction();
- if (action == MotionEvent.ACTION_UP) {
- circles.add(new BallDrawing(event.getX(),event.getY()));
- }
- return true;
- }
- Drawable drawable;
- Rect drawableBounds = null;
- private void init() {
- backgroundPaint.setColor(Color.BLUE);
- drawable = getResources().getDrawable(R.drawable.bal);
- if (drawable != null) {
- drawable.setBounds(0,0,40,40);
- drawableBounds = drawable.getBounds();
- }
- Thread t = new Thread(new Runnable() {
- @Override
- public void run() {
- while (true) {
- try {
- Thread.sleep(100);
- tick();
- } catch (InterruptedException e) {
- return;
- }
- }
- }
- });
- t.start();
- }
- public void tick() {
- activity.runOnUiThread(new Runnable() {
- @Override
- public void run() {
- for (BallDrawing circle : circles) {
- circle.translate(random.nextInt(10) - 5, random.nextInt(10) - 5);
- }
- }
- });
- }
- @Override
- protected void onDraw(Canvas canvas) {
- for (BallDrawing c : circles) {
- c.draw(canvas);
- }
- }
- private class BallDrawing {
- public float cx, cy;
- public BallDrawing(float cx, float cy) {
- this.cx = cx;
- this.cy = cy;
- }
- public void translate(int dx, int dy) {
- invalidate((int)cx + drawableBounds.left,(int)cy + drawableBounds.top, (int)cx+1 + drawableBounds.right, (int)cy+1 + drawableBounds.bottom);
- cx += dx;
- cy += dy;
- invalidate((int)cx + drawableBounds.left,(int)cy + drawableBounds.top, (int)cx + 1 + drawableBounds.right, (int)cy+1 + drawableBounds.bottom);
- }
- public void draw(Canvas canvas) {
- canvas.save();
- canvas.translate(cx,cy);
- drawable.draw(canvas);
- canvas.restore();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement