Thursday, December 19, 2013

andEngine full screen image backGround & jumping sprite

download: http://www.mediafire.com/download/xmj35iv0ovkz30o/jumpSprite(2).zip






package com.example.animationsprite;

import org.andengine.engine.camera.Camera;
import org.andengine.engine.options.EngineOptions;
import org.andengine.engine.options.ScreenOrientation;
import org.andengine.engine.options.resolutionpolicy.FillResolutionPolicy;
import org.andengine.entity.primitive.Rectangle;
import org.andengine.entity.scene.IOnSceneTouchListener;
import org.andengine.entity.scene.Scene;
import org.andengine.entity.scene.background.Background;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.util.FPSLogger;
import org.andengine.extension.physics.box2d.PhysicsConnector;
import org.andengine.extension.physics.box2d.PhysicsFactory;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.extension.physics.box2d.util.Vector2Pool;
import org.andengine.input.sensor.acceleration.AccelerationData;
import org.andengine.input.sensor.acceleration.IAccelerationListener;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.TextureOptions;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory;
import org.andengine.opengl.texture.atlas.bitmap.BuildableBitmapTextureAtlas;
import org.andengine.opengl.texture.atlas.bitmap.source.IBitmapTextureAtlasSource;
import org.andengine.opengl.texture.atlas.buildable.builder.BlackPawnTextureAtlasBuilder;
import org.andengine.opengl.texture.atlas.buildable.builder.ITextureAtlasBuilder.TextureAtlasBuilderException;
import org.andengine.opengl.texture.region.ITextureRegion;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.opengl.vbo.VertexBufferObjectManager;
import org.andengine.ui.activity.SimpleBaseGameActivity;
import org.andengine.util.debug.Debug;

import android.hardware.SensorManager;

import com.badlogic.gdx.math.Vector2;
import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.BodyDef.BodyType;
import com.badlogic.gdx.physics.box2d.FixtureDef;

public class MainActivity extends SimpleBaseGameActivity implements
        IAccelerationListener {

    private static final int CAMERA_WIDTH = 360;
    private static final int CAMERA_HEIGHT = 240;

    private BitmapTextureAtlas mBitmapTextureAtlas,
            backgroundBitmapTextureAtlas;

    private TiledTextureRegion mBoxFaceTextureRegion;
    ITextureRegion backgroundTiledTextureRegion;

    private int mFaceCount = 0;

    private PhysicsWorld mPhysicsWorld;

    float mGravityX;
    float mGravityY;

    private Scene mScene;

    AnimatedSprite faceAnimatedSprite;
    Body bodyFace;
    FixtureDef faceFixtureDef = PhysicsFactory.createFixtureDef(100, 0.1f, 0.0f),
            wallFixtureDef = PhysicsFactory.createFixtureDef(0, 0.0f, 0.0f);

    Camera camera;
    BuildableBitmapTextureAtlas mBuildableBitmapTextureAtlas;

    Sprite backGroundSprite;

    @Override
    public EngineOptions onCreateEngineOptions() {

        camera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT);

        return new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED,
                new FillResolutionPolicy(), camera);
    }

    @Override
    public void onCreateResources()

    {
        BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/");

        // this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(
        // this.getTextureManager(), 1024, 512, TextureOptions.DEFAULT);

        this.mBuildableBitmapTextureAtlas = new BuildableBitmapTextureAtlas(
                this.getTextureManager(), 1024, 512, TextureOptions.DEFAULT);

        setBackgroundImage();

       

        this.mBitmapTextureAtlas = new BitmapTextureAtlas(
                this.getTextureManager(), 64, 64, TextureOptions.BILINEAR);
        this.mBoxFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory
                .createTiledFromAsset(this.mBitmapTextureAtlas, this,
                        "face_box_tiled.png", 0, 0, 2, 1); // 64x32

        this.mBitmapTextureAtlas.load();

        try {
            this.mBuildableBitmapTextureAtlas
                    .build(new BlackPawnTextureAtlasBuilder<IBitmapTextureAtlasSource, BitmapTextureAtlas>(
                            0, 0, 1));
            this.mBuildableBitmapTextureAtlas.load();
        } catch (TextureAtlasBuilderException e) {
            Debug.e(e);
        }
    }

    void setBackgroundImage() {
        this.backgroundBitmapTextureAtlas = new BitmapTextureAtlas(
                this.getTextureManager(), 512, 1024, TextureOptions.NEAREST_PREMULTIPLYALPHA);
        backgroundTiledTextureRegion = BitmapTextureAtlasTextureRegionFactory
                .createFromAsset(backgroundBitmapTextureAtlas, this,
                        "background_sky.png", 0, 0);
        this.backgroundBitmapTextureAtlas.load();

    }

    @Override
    public Scene onCreateScene() {
        this.mEngine.registerUpdateHandler(new FPSLogger());

        this.mPhysicsWorld = new PhysicsWorld(new Vector2(0,
                SensorManager.GRAVITY_EARTH), false);

        this.mScene = new Scene();
        // this.mScene.setBackground(new Background(0, 0, 0));
        backGroundSprite = new Sprite(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT,
                this.backgroundTiledTextureRegion,
                this.getVertexBufferObjectManager());

        // scene.setBackground(new Background(Color.WHITE));
        mScene.setBackgroundEnabled(false);
        this.mScene.attachChild(backGroundSprite);

        create_4_Wall();

        create_face_sprite();

        mScene.setOnSceneTouchListener(new IOnSceneTouchListener() {

            @Override
            public boolean onSceneTouchEvent(Scene pScene,
                    TouchEvent pSceneTouchEvent) {

                if (pSceneTouchEvent.isActionDown()) {
                    // body.setLinearVelocity(new
                    // Vector2(body.getLinearVelocity().x,-8f));
                    jumpFace(bodyFace);

                }
                return false;
            }
        });

        return this.mScene;
    }

    private void create_face_sprite() {
        // for sprite
        faceAnimatedSprite = new AnimatedSprite(200, 200,
                this.mBoxFaceTextureRegion, this.getVertexBufferObjectManager());

        bodyFace = PhysicsFactory.createBoxBody(this.mPhysicsWorld,
                faceAnimatedSprite, BodyType.DynamicBody, faceFixtureDef);
        faceAnimatedSprite.animate(new long[] { 200, 200 }, 0, 1, true);
        faceAnimatedSprite.setUserData(bodyFace);
        // this.mScene.registerTouchArea(face);

        // physicsHandler = new PhysicsHandler(face);
        // face.registerUpdateHandler(physicsHandler);
        this.mScene.attachChild(faceAnimatedSprite);
        this.mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(
                faceAnimatedSprite, bodyFace, true, true));
        // end for sprite

    }

    private void create_4_Wall() {
        final VertexBufferObjectManager vertexBufferObjectManager = this
                .getVertexBufferObjectManager();
        final Rectangle ground = new Rectangle(0, CAMERA_HEIGHT - 2,
                CAMERA_WIDTH, 2, vertexBufferObjectManager);
        final Rectangle roof = new Rectangle(0, 0, CAMERA_WIDTH, 2,
                vertexBufferObjectManager);
        final Rectangle left = new Rectangle(0, 0, 2, CAMERA_HEIGHT,
                vertexBufferObjectManager);
        final Rectangle right = new Rectangle(CAMERA_WIDTH - 2, 0, 2,
                CAMERA_HEIGHT, vertexBufferObjectManager);

        PhysicsFactory.createBoxBody(this.mPhysicsWorld, ground,
                BodyType.StaticBody, wallFixtureDef);
        PhysicsFactory.createBoxBody(this.mPhysicsWorld, roof,
                BodyType.StaticBody, wallFixtureDef);
        PhysicsFactory.createBoxBody(this.mPhysicsWorld, left,
                BodyType.StaticBody, wallFixtureDef);
        PhysicsFactory.createBoxBody(this.mPhysicsWorld, right,
                BodyType.StaticBody, wallFixtureDef);

        this.mScene.attachChild(ground);
        this.mScene.attachChild(roof);
        this.mScene.attachChild(left);
        this.mScene.attachChild(right);

        this.mScene.registerUpdateHandler(this.mPhysicsWorld);

    }

    @Override
    public void onAccelerationAccuracyChanged(
            final AccelerationData pAccelerationData) {

    }

    @Override
    public void onAccelerationChanged(final AccelerationData pAccelerationData) {
        this.mGravityX = pAccelerationData.getX();
        this.mGravityY = pAccelerationData.getY();

        final Vector2 gravity = Vector2Pool.obtain(this.mGravityX,
                this.mGravityY);

        // this.mPhysicsWorld.setVelocityIterations(10);
        this.mPhysicsWorld.setGravity(gravity);
        Vector2Pool.recycle(gravity);
    }

    @Override
    public void onResumeGame() {
        super.onResumeGame();

        this.enableAccelerationSensor(this);
    }

    @Override
    public void onPauseGame() {
        super.onPauseGame();

        this.disableAccelerationSensor();
    }

    void jumpFace(Body _body) {

        Body body = _body;

        Vector2 velocity = Vector2Pool.obtain(0, -5);

        // Vector2 velocity = Vector2Pool.obtain(10, 10);

        body.setLinearVelocity(velocity);
        Vector2Pool.recycle(velocity);

    }

}

Wednesday, December 11, 2013

android proximity sensor

download:  http://www.mediafire.com/download/83nnqx9cnhw5nsv/AndroidProximitySensor_110920a.zip







another
-------------------------------------------

01import android.app.Activity;
02import android.hardware.Sensor;
03import android.hardware.SensorEvent;
04import android.hardware.SensorEventListener;
05import android.hardware.SensorManager;
06import android.os.Bundle;
07import android.widget.ImageView;
08 
09public class SensorActivity extends Activity implements SensorEventListener {
10 private SensorManager mSensorManager;
11 private Sensor mSensor;
12 ImageView iv;
13 
14 @Override
15 protected void onCreate(Bundle savedInstanceState) {
16  // TODO Auto-generated method stub
17  super.onCreate(savedInstanceState);
18  setContentView(R.layout.sensor_screen);
19  mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
20  mSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_PROXIMITY);
21  iv = (ImageView) findViewById(R.id.imageView1);
22 }
23 
24 protected void onResume() {
25  super.onResume();
26  mSensorManager.registerListener(this, mSensor,
27    SensorManager.SENSOR_DELAY_NORMAL);
28 }
29 
30 protected void onPause() {
31  super.onPause();
32  mSensorManager.unregisterListener(this);
33 }
34 
35 public void onAccuracyChanged(Sensor sensor, int accuracy) {
36 }
37 
38 public void onSensorChanged(SensorEvent event) {
39  if (event.values[0] == 0) {
40   iv.setImageResource(R.drawable.near);
41  } else {
42   iv.setImageResource(R.drawable.far);
43  }
44 }
45}

Sunday, December 1, 2013

get display density in android

DisplayMetrics metrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metrics);
        switch (metrics.densityDpi) {
        case DisplayMetrics.DENSITY_LOW:
            break;
        case DisplayMetrics.DENSITY_MEDIUM:
            break;
        case DisplayMetrics.DENSITY_HIGH:
            PASSED_DISTANCE = 200;
            break;
        }

android multitouch or touch 2 button at a time by multitouch



download:   http://www.mediafire.com/download/3obheaff1ut7sgl/MultiTouchHandler.zip


import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

    Button button1, button2 ;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        button1 = (Button)findViewById(R.id.button1);
        button2 = (Button)findViewById(R.id.button2);

        RelativeLayout myLayout = (RelativeLayout) findViewById(R.id.rl1);

        button1.setOnTouchListener(new RelativeLayout.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent m) {
                handleTouch(m);
                return true;
            }
        });
       
        button2.setOnTouchListener(new RelativeLayout.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent m) {
                handleTouch(m);
                return true;
            }
        });
    }
   
    void handleTouch(MotionEvent m)
    {
           
           
            int pointerCount = m.getPointerCount();
           
            for (int i = 0; i < pointerCount; i++)
            {
                int x = (int) m.getX(i);
                int y = (int) m.getY(i);           
                int id = m.getPointerId(i);
                int action = m.getActionMasked();
                int actionIndex = m.getActionIndex();
                String actionString;
               
               
                switch (action)
                {
                    case MotionEvent.ACTION_DOWN:
                        actionString = "DOWN";
                        break;
                    case MotionEvent.ACTION_UP:
                        actionString = "UP";
                        break;   
                    case MotionEvent.ACTION_POINTER_DOWN:
                        actionString = "PNTR DOWN";
                        break;
                    case MotionEvent.ACTION_POINTER_UP:
                        actionString = "PNTR UP";
                        break;
                    case MotionEvent.ACTION_MOVE:
                        actionString = "MOVE";
                        break;
                    default:
                        actionString = "";
                }
               
                String touchStatus = "Action: " + actionString + " Index: " + actionIndex + " ID: " + id + " X: " + x + " Y: " + y+ " pointerCount="+pointerCount;
               
                if (pointerCount == 1)
                    button1.setText(touchStatus);
                else
                    button2.setText(touchStatus);
            }
    }

}

android phone status & subscriber id

Thursday, November 14, 2013

android json with post method response

try {
           
         URL url = new URL("http://www.htmlgoon.com/api/POST_JSON_Service.php");
           
            JSONObject jo = new JSONObject();

           
            jo.put("firstname", "abc");
            jo.put("lastname", "xyz");
            jo.put("city", "Bengalore");

           
//            jo.put("userID", "6268656283cfcc32b07340e5a9d7aceec747b316");
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url.toURI());
            // // Set up the header types needed to properly transfer JSON
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept", "JSON");
            httpPost.setHeader("Accept-Encoding", "application/json");
            httpPost.setHeader("Accept-Language", "en-US");
            //
            // // Prepare JSON to send by setting the entity
            httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));
            //

            // //
            // // Execute POST
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

            Log.d("===========", "HTTP: OK");
        } catch (Exception e) {
            Log.e("*********", "Error in http connection " + e.toString());
        }
        //
        // // Convert response to string
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    is, "UTF-8"));

            sb = new StringBuilder();

            String line = null;
            //
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }

            is.close();

            result = sb.toString();
            //
            Log.e("&&&&&&&&&&&&", "result=" + result);
        } catch (Exception e) {
            Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
                    .show();
        }
        // END Convert response to string

api testing webtie

Sunday, August 18, 2013

run a function after fixed time

import java.util.Timer;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class TimerTest
{
   
   
   
    public static void main(String[] args)
    {
//        Timer timer = new Timer();
//        timer.schedule(new MyTask(), 100);
//       
//       
//       
//        new Thread( new MyThread() ).start();
//////       
//        for(int k=0; k<5; k++ ){
//           
//            try
//            {
//                System.out.println("main() k="+k);
//                Thread.sleep(100);
//            }
//            catch (InterruptedException e)
//            {
//                e.printStackTrace();
//            }
//        }
//       
//        //creates thread pool of size 2
//        ScheduledThreadPoolExecutor threadPool = new ScheduledThreadPoolExecutor(2);
//        threadPool.schedule(new MyTask1(), 1, TimeUnit.MILLISECONDS);
//        threadPool.schedule(new MyTask2(), 1, TimeUnit.MILLISECONDS);
       
        ScheduledExecutorService scheduleTaskExecutor;
        scheduleTaskExecutor= Executors.newScheduledThreadPool(5);

        // This schedule a task to run every 10 minutes:
        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
          public void run() {
            // Parsing RSS feed:
              System.out.println("scheduleTaskExecutor run() i=");

            // If you need update UI, simply do this:
          
          }
        }, 0, 5, TimeUnit.SECONDS);
       
    }

}

class MyThread implements Runnable
{
    @Override
    public void run()
    {
        try
        {
            for(int i=0; i<5; i++ )
            {
                Thread.sleep(300);
                System.out.println("My thread run() i="+i);
            }
           
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
       
       
       
    }
}

class MyTask extends java.util.TimerTask {
    public void run()
    {
        for(int i=0; i<5; i++ )
        {
            try {
                System.out.println("Timer run() i="+i);
                Thread.sleep(100);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
           
        }
       
    }
}

class MyTask1 implements Runnable
{
   public void run()
   {
       try
        {
            for(int i=0; i<5; i++ )
            {
                Thread.sleep(300);
                System.out.println("----Sche 1 is running");
            }
           
        }
        catch (InterruptedException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
     
   }
}
class MyTask2 implements Runnable
{
   public void run()
   {
     
      try
        {
            for(int i=0; i<5; i++ )
            {
                Thread.sleep(300);
                System.out.println(">>>>>Sche 2 is running");
            }
           
        }
        catch (InterruptedException e)
        {
            e.printStackTrace();
        }
   }
}

Wednesday, August 14, 2013

circle imageView extend ImageView

download: http://www.mediafire.com/download/z8uhdci7hp1831z/CircleView.tar





package com.home.istiaq;



import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.Paint.Style;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
import android.graphics.drawable.BitmapDrawable;
import android.util.AttributeSet;
import android.widget.ImageView;

public class ImageViewRounded extends ImageView {

    public ImageViewRounded(Context context) {
        super(context);
    }

    public ImageViewRounded(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public ImageViewRounded(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        BitmapDrawable drawable = (BitmapDrawable) getDrawable();

        if (drawable == null) {
            return;
        }

        if (getWidth() == 0 || getHeight() == 0) {
            return;
        }

        Bitmap fullSizeBitmap = drawable.getBitmap();

        int scaledWidth = getMeasuredWidth();
        int scaledHeight = getMeasuredHeight();

        Bitmap mScaledBitmap;
        if (scaledWidth == fullSizeBitmap.getWidth()
                && scaledHeight == fullSizeBitmap.getHeight()) {
            mScaledBitmap = fullSizeBitmap;
        } else {
            mScaledBitmap = Bitmap.createScaledBitmap(fullSizeBitmap,
                    scaledWidth, scaledHeight, true /* filter */);
        }

        // Bitmap roundBitmap = getRoundedCornerBitmap(mScaledBitmap);

        // Bitmap roundBitmap = getRoundedCornerBitmap(getContext(),
        // mScaledBitmap, 10, scaledWidth, scaledHeight, false, false,
        // false, false);
        // canvas.drawBitmap(roundBitmap, 0, 0, null);

        Bitmap circleBitmap = getCircledBitmap(mScaledBitmap);

        canvas.drawBitmap(circleBitmap, 0, 0, null);

    }

    public Bitmap getRoundedCornerBitmap(Context context, Bitmap input,
            int pixels, int w, int h, boolean squareTL, boolean squareTR,
            boolean squareBL, boolean squareBR) {

        Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
        Canvas canvas = new Canvas(output);
        final float densityMultiplier = context.getResources()
                .getDisplayMetrics().density;

        final int color = 0xff424242;

        final Paint paint = new Paint();
        final Rect rect = new Rect(0, 0, w, h);
        final RectF rectF = new RectF(rect);

        // make sure that our rounded corner is scaled appropriately
        final float roundPx = pixels * densityMultiplier;

        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);

        // draw rectangles over the corners we want to be square
        if (squareTL) {
            canvas.drawRect(0, 0, w / 2, h / 2, paint);
        }
        if (squareTR) {
            canvas.drawRect(w / 2, 0, w, h / 2, paint);
        }
        if (squareBL) {
            canvas.drawRect(0, h / 2, w / 2, h, paint);
        }
        if (squareBR) {
            canvas.drawRect(w / 2, h / 2, w, h, paint);
        }

        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        canvas.drawBitmap(input, 0, 0, paint);

        return output;
    }

    Bitmap getCircledBitmap(Bitmap bitmap) {

        Bitmap result = Bitmap.createBitmap(bitmap.getWidth(),
                bitmap.getHeight(), Bitmap.Config.ARGB_8888);
       
       
       
       

       
        Canvas canvas = new Canvas(result);

        int color = Color.BLUE;
        Paint paint = new Paint();
        Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());
       
        paint.setAntiAlias(true);
        canvas.drawARGB(0, 0, 0, 0);
        paint.setColor(color);
//        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
        canvas.drawCircle(bitmap.getWidth()/2, bitmap.getHeight()/2, bitmap.getHeight()/2, paint);

        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
        canvas.drawBitmap(bitmap, rect, rect, paint);
       


        return result;
    }

}

Sunday, July 14, 2013

flood fill in android



Main.java
------------------------
package com.example.floodfill;

import java.util.LinkedList;
import java.util.Queue;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.Point;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;

public class Main extends Activity {

    private RelativeLayout dashBoard;
    private MyView myView;
    public ImageView image;

    Button b_red, b_blue, b_green, b_orange, b_clear;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        myView = new MyView(this);
        setContentView(R.layout.activity_main);
        findViewById(R.id.dashBoard);

        b_red = (Button) findViewById(R.id.b_red);
        b_blue = (Button) findViewById(R.id.b_blue);
        b_green = (Button) findViewById(R.id.b_green);
        b_orange = (Button) findViewById(R.id.b_orange);

        b_red.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myView.changePaintColor(0xFFFF0000);
            }
        });

        b_blue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myView.changePaintColor(0xFF0000FF);
            }
        });

        b_green.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myView.changePaintColor(0xFF00FF00);
            }
        });

        b_orange.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                myView.changePaintColor(0xFFFF9900);
            }
        });

        dashBoard = (RelativeLayout) findViewById(R.id.dashBoard);
        dashBoard.addView(myView);

    }

    public class MyView extends View {

        private Paint paint;
        private Path path;
        public Bitmap mBitmap;
        public ProgressDialog pd;
        final Point p1 = new Point();
        public Canvas canvas;

        // Bitmap mutableBitmap ;
        public MyView(Context context) {

            super(context);

            this.paint = new Paint();
            this.paint.setAntiAlias(true);
            pd = new ProgressDialog(context);
            this.paint.setStyle(Paint.Style.STROKE);
            paint.setStrokeJoin(Paint.Join.ROUND);
            paint.setStrokeWidth(5f);
            mBitmap = BitmapFactory.decodeResource(getResources(),
                    R.drawable.sepia_origin).copy(Bitmap.Config.ARGB_8888, true);
            this.path = new Path();
        }

        @Override
        protected void onDraw(Canvas canvas) {
            this.canvas = canvas;
            this.paint.setColor(Color.RED);

            canvas.drawBitmap(mBitmap, 0, 0, paint);
        }

        @Override
        public boolean onTouchEvent(MotionEvent event) {

            float x = event.getX();
            float y = event.getY();

            switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:

                p1.x = (int) x;
                p1.y = (int) y;
                final int sourceColor = mBitmap.getPixel((int) x, (int) y);
                final int targetColor = paint.getColor();
                new TheTask(mBitmap, p1, sourceColor, targetColor).execute();
                invalidate();
            }
            return true;
        }

        public void clear() {
            path.reset();
            invalidate();
        }

        public int getCurrentPaintColor() {
            return paint.getColor();
        }

        public void changePaintColor(int color) {
            this.paint.setColor(color);
        }

        class TheTask extends AsyncTask<Void, Integer, Void> {

            Bitmap bmp;
            Point pt;
            int replacementColor, targetColor;

            public TheTask(Bitmap bm, Point p, int sc, int tc) {
                this.bmp = bm;
                this.pt = p;
                this.replacementColor = tc;
                this.targetColor = sc;
                pd.setMessage("Filling....");
                pd.show();
            }

            @Override
            protected void onPreExecute() {
                pd.show();

            }

            @Override
            protected void onProgressUpdate(Integer... values) {

            }

            @Override
            protected Void doInBackground(Void... params) {
                FloodFill f = new FloodFill();
                f.floodFill(bmp, pt, targetColor, replacementColor);
                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                pd.dismiss();
                invalidate();
            }
        }
    }

    // flood fill
    public class FloodFill {

        public void floodFill(Bitmap image, Point node, int targetColor,
                int replacementColor) {

            int width = image.getWidth();
            int height = image.getHeight();
            int target = targetColor;
            int replacement = replacementColor;

            if (target != replacement) {
                Queue<Point> queue = new LinkedList<Point>();
                do {

                    int x = node.x;
                    int y = node.y;
                    while (x > 0 && image.getPixel(x - 1, y) == target) {
                        x--;
                    }

                    boolean spanUp = false;
                    boolean spanDown = false;
                    while (x < width && image.getPixel(x, y) == target) {
                        image.setPixel(x, y, replacement);
                        if (!spanUp && y > 0
                                && image.getPixel(x, y - 1) == target) {
                            queue.add(new Point(x, y - 1));
                            spanUp = true;
                        } else if (spanUp && y > 0
                                && image.getPixel(x, y - 1) != target) {
                            spanUp = false;
                        }
                        if (!spanDown && y < height - 1
                                && image.getPixel(x, y + 1) == target) {
                            queue.add(new Point(x, y + 1));
                            spanDown = true;
                        } else if (spanDown && y < (height - 1)
                                && image.getPixel(x, y + 1) != target) {
                            spanDown = false;
                        }
                        x++;
                    }

                } while ((node = queue.poll()) != null);
            }
        }
    }
}



activity_main.xml
----------------------------------

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/drawingLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Main" >

<RelativeLayout
    android:id="@+id/dashBoard"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/b_red"
    android:layout_alignParentLeft="true"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_marginBottom="10dp" >

</RelativeLayout>

<Button
    android:id="@+id/b_red"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:background="#FF0000" />

<Button
    android:id="@+id/b_green"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/b_red"
    android:background="#00FF00" />

<Button
    android:id="@+id/b_blue"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/b_green"
    android:background="#0000FF" />

<Button
    android:id="@+id/b_orange"
    android:layout_width="65dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_toRightOf="@+id/b_blue"
    android:background="#FF9900" />

<Button
    android:id="@+id/button5"
    android:layout_width="60dp"
    android:layout_height="40dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:text="Clear" />

</RelativeLayout>

Friday, July 12, 2013

image effect


package com.example.imageprocessing;

import java.util.Random;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BlurMaskFilter;
import android.graphics.BlurMaskFilter.Blur;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.os.Bundle;
import android.widget.ImageView;

//all effects are taken from http://xjaphx.wordpress.com/learning/tutorials/

public class MainActivity extends Activity {
    public static final double PI = 3.14159d;
    public static final double FULL_CIRCLE_DEGREE = 360d;
    public static final double HALF_CIRCLE_DEGREE = 180d;
    public static final double RANGE = 256d;
   
    ImageView ivBeforeEffect, ivAfterEffect;

    Bitmap bmpInput, bmpOutput;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ivBeforeEffect = (ImageView) findViewById(R.id.ivBeforeEffect);
        ivAfterEffect = (ImageView) findViewById(R.id.ivAfterEffect);

        bmpInput = BitmapFactory.decodeResource(getResources(),
                R.drawable.whitechapel);

        ivBeforeEffect.setImageBitmap(bmpInput);

//        bmpInput = getGreyscale(bmpInput);
        // bmpOutput = getHighlightImage(bmpInput);
        // bmpOutput = doInvert(bmpInput);
//        bmpOutput = getSnowEffect(bmpInput);
        bmpInput = getTintImage(bmpInput, 290);
       
        bmpOutput = getGreyscale(bmpInput);

        ivAfterEffect.setImageBitmap(bmpOutput);

    }

    public static Bitmap getGreyscale(Bitmap src) {
        // constant factors
        final double GS_RED = 0.299;
        final double GS_GREEN = 0.587;
        final double GS_BLUE = 0.114;

        // create output bitmap
        Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
                src.getConfig());
        // pixel information
        int A, R, G, B;
        int pixel;

        // get image size
        int width = src.getWidth();
        int height = src.getHeight();

        // scan through every single pixel
        for (int x = 0; x < width; ++x) {
            for (int y = 0; y < height; ++y) {
                // get one pixel color
                pixel = src.getPixel(x, y);
                // retrieve color of all channels
                A = Color.alpha(pixel);
                R = Color.red(pixel);
                G = Color.green(pixel);
                B = Color.blue(pixel);
               
                if(x < width/2 && y<height/2)
                {
                    R = G = B = (int) (GS_RED * R + GS_GREEN * G + GS_BLUE * B);
                }
                // take conversion up to one single value
//                R = G = B = (int) (GS_RED * R + GS_GREEN * G + GS_BLUE * B);
                // set new pixel color to output bitmap
                bmOut.setPixel(x, y, Color.argb(A, R, G, B));
            }
        }

        // return final image
        return bmOut;
    }

    public static Bitmap getHighlightImage(Bitmap src) {
        // create new bitmap, which will be painted and becomes result image
        Bitmap bmOut = Bitmap.createBitmap(src.getWidth() + 96,
                src.getHeight() + 96, Bitmap.Config.ARGB_8888);
        // setup canvas for painting
        Canvas canvas = new Canvas(bmOut);
        // setup default color
        canvas.drawColor(0, PorterDuff.Mode.CLEAR);

        // create a blur paint for capturing alpha
        Paint ptBlur = new Paint();
        ptBlur.setMaskFilter(new BlurMaskFilter(15, Blur.NORMAL));
        int[] offsetXY = new int[2];
        // capture alpha into a bitmap
        Bitmap bmAlpha = src.extractAlpha(ptBlur, offsetXY);
        // create a color paint
        Paint ptAlphaColor = new Paint();
        ptAlphaColor.setColor(0xFFFFFFFF);
        // paint color for captured alpha region (bitmap)
        canvas.drawBitmap(bmAlpha, offsetXY[0], offsetXY[1], ptAlphaColor);
        // free memory
        bmAlpha.recycle();

        // paint the image source
        canvas.drawBitmap(src, 0, 0, null);

        // return out final image
        return bmOut;
    }

    public static Bitmap doInvert(Bitmap src) {
        // create new bitmap with the same settings as source bitmap
        Bitmap bmOut = Bitmap.createBitmap(src.getWidth(), src.getHeight(),
                src.getConfig());
        // color info
        int A, R, G, B;
        int pixelColor;
        // image size
        int height = src.getHeight();
        int width = src.getWidth();

        // scan through every pixel
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                // get one pixel
                pixelColor = src.getPixel(x, y);
                // saving alpha channel
                A = Color.alpha(pixelColor);
                // inverting byte for each R/G/B channel
                R = 255 - Color.red(pixelColor);
                G = 255 - Color.green(pixelColor);
                B = 255 - Color.blue(pixelColor);
                // set newly-inverted pixel to output image
                bmOut.setPixel(x, y, Color.argb(A, R, G, B));
            }
        }

        // return final bitmap
        return bmOut;
    }

    public static Bitmap getSnowEffect(Bitmap source) {
        // get image size
        int width = source.getWidth();
        int height = source.getHeight();
        int[] pixels = new int[width * height];
        int COLOR_MAX = 0xff;
        // get pixel array from source
        source.getPixels(pixels, 0, width, 0, 0, width, height);
        // random object
        Random random = new Random();

        int R, G, B, index = 0, thresHold = 50;
        // iteration through pixels
        for (int y = 0; y < height; ++y) {
            for (int x = 0; x < width; ++x) {
                // get current index in 2D-matrix
                index = y * width + x;
                // get color
                R = Color.red(pixels[index]);
                G = Color.green(pixels[index]);
                B = Color.blue(pixels[index]);
                // generate threshold
                thresHold = random.nextInt(COLOR_MAX);
                if (R > thresHold && G > thresHold && B > thresHold) {
                    pixels[index] = Color.rgb(COLOR_MAX, COLOR_MAX, COLOR_MAX);
                }
            }
        }
        // output bitmap
        Bitmap bmOut = Bitmap
                .createBitmap(width, height, Bitmap.Config.RGB_565);
        bmOut.setPixels(pixels, 0, width, 0, 0, width, height);
        return bmOut;
    }

    public static Bitmap getTintImage(Bitmap src, int degree) {
       

        int width = src.getWidth();
        int height = src.getHeight();

        int[] pix = new int[width * height];
        src.getPixels(pix, 0, width, 0, 0, width, height);

        int RY, GY, BY, RYY, GYY, BYY, R, G, B, Y;
        double angle = (PI * (double) degree) / HALF_CIRCLE_DEGREE;

        int S = (int) (RANGE * Math.sin(angle));
        int C = (int) (RANGE * Math.cos(angle));

        for (int y = 0; y < height; y++)
            for (int x = 0; x < width; x++) {
                int index = y * width + x;
                int r = (pix[index] >> 16) & 0xff;
                int g = (pix[index] >> 8) & 0xff;
                int b = pix[index] & 0xff;
                RY = (70 * r - 59 * g - 11 * b) / 100;
                GY = (-30 * r + 41 * g - 11 * b) / 100;
                BY = (-30 * r - 59 * g + 89 * b) / 100;
                Y = (30 * r + 59 * g + 11 * b) / 100;
                RYY = (S * BY + C * RY) / 256;
                BYY = (C * BY - S * RY) / 256;
                GYY = (-51 * RYY - 19 * BYY) / 100;
                R = Y + RYY;
                R = (R < 0) ? 0 : ((R > 255) ? 255 : R);
                G = Y + GYY;
                G = (G < 0) ? 0 : ((G > 255) ? 255 : G);
                B = Y + BYY;
                B = (B < 0) ? 0 : ((B > 255) ? 255 : B);
                pix[index] = 0xff000000 | (R << 16) | (G << 8) | B;
            }

        Bitmap outBitmap = Bitmap.createBitmap(width, height, src.getConfig());
        outBitmap.setPixels(pix, 0, width, 0, 0, width, height);

        pix = null;

        return outBitmap;
    }

}

activity_main.xml
______________________
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:background="@android:color/black"
     >

    <ImageView
        android:id="@+id/ivBeforeEffect"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
       
        android:src="@drawable/ic_launcher"
        android:layout_weight="1.0" />
   
    <ImageView
        android:id="@+id/ivAfterEffect"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
       
        android:src="@drawable/ic_launcher"
         android:layout_weight="1.0" />

</LinearLayout>

Wednesday, July 3, 2013

progress dialog in android

download: http://www.mediafire.com/download/ou7hmypj3iynwdc/ProgressDialogExample.tar.gz

package com.helloandroid.android.progressdialogexample;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.widget.TextView;

public class ProgressDialogExample extends Activity implements Runnable {

private String pi_string;
private TextView tv;
private ProgressDialog pd;

@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);

tv = (TextView) this.findViewById(R.id.main);
tv.setText("Press any key to start calculation");
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

pd = ProgressDialog.show(this, "Working..", "Calculating Pi", true,
false);

Thread thread = new Thread(this);
thread.start();

return super.onKeyDown(keyCode, event);
}

public void run() {
pi_string = Pi.computePi(800).toString();
handler.sendEmptyMessage(0);
}

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
pd.dismiss();
tv.setText(pi_string);

}
};

}