Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.example;
- import java.util.Random;
- import android.app.Activity;
- import android.content.Context;
- import android.graphics.Bitmap;
- import android.graphics.Canvas;
- import android.graphics.Color;
- import android.graphics.Paint;
- import android.os.Bundle;
- import android.os.Handler;
- import android.os.Message;
- import android.util.AttributeSet;
- import android.util.Log;
- import android.view.View;
- public class Test1 extends Activity {
- /** Called when the activity is first created. */
- private Handler mHandler;
- private DrawView draw;
- private boolean running;
- @Override
- public void onCreate(Bundle savedInstanceState) {
- super.onCreate(savedInstanceState);
- draw = new DrawView(this, null);
- mHandler = new Handler(new Handler.Callback() {
- @Override
- public boolean handleMessage(Message msg) {
- Log.v("tag", "add random point in 500 ms");
- draw.addRandomPoint();
- if (running)
- mHandler.sendMessageDelayed(new Message(), 500);
- return true;
- }
- });
- setContentView(draw);
- }
- @Override
- public void onResume() {
- super.onResume();
- running = true;
- mHandler.sendMessage(new Message());
- }
- @Override
- public void onPause() {
- super.onPause();
- running = false;
- }
- public class DrawView extends View {
- public static final String TAG = "DrawView";
- Paint paint = new Paint();
- Bitmap cache;
- public DrawView(Context context, AttributeSet attrs) {
- super(context, attrs);
- paint.setStyle(Paint.Style.FILL_AND_STROKE);
- paint.setColor(Color.WHITE);
- paint.setAntiAlias(true);
- }
- @Override
- public void onDraw(Canvas canvas) {
- if (cache != null)
- canvas.drawBitmap(cache, 0, 0, paint);
- }
- Random random = new Random();
- private final int[] RAINBOW = {Color.RED, Color.YELLOW, Color.BLUE, Color.GREEN,
- Color.parseColor("#FF7F00"), //orange
- Color.parseColor("#00ffff"),//azure
- Color.parseColor("#8b00ff") //purple
- };
- public void addRandomPoint() {
- int w = getWidth();
- int h = getHeight();
- if (w == 0 || h == 0)
- return;
- Point point = new Point(
- random.nextFloat() * getWidth(),
- random.nextFloat() * getHeight(),
- random.nextFloat() * 30,
- RAINBOW[random.nextInt(RAINBOW.length)]);
- if (cache == null) {
- cache = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
- }
- Canvas canvas = new Canvas(cache);
- paint.setColor(point.color);
- paint.setStyle((random.nextFloat()> 0.5) ? Paint.Style.STROKE : Paint.Style.FILL_AND_STROKE);
- paint.setStrokeWidth(point.radius / 5);
- canvas.drawCircle(point.x, point.y, point.radius, paint);
- postInvalidate();
- }
- }
- class Point {
- Point(float x, float y, float radius, int color) {
- this.x = x;
- this.y = y;
- this.radius = radius;
- this.color = color;
- }
- float x, y, radius;
- int color;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement