Friday 18 October 2013

Quick pop-up with animation like Google Chrome .

Quick pop-up same as Google Chrome which appear when you first time start Chrome.
Here in this pop-up use animation which will be used to create a floating fill to pop-up.

How to use ?
QuickPopup quickPopup = new QuickPopup(MainActivity.this, "Hi :)");
quickPopup.show(view);

QuickPopup.java

public class QuickPopup {

protected WindowManager mWindowManager;
protected Context mContext;
protected Drawable mBackgroundDrawable = null;
protected PopupWindow mWindow;
private TextView txtShow;
private ImageView imgUp, imgDown;
protected View mView;
protected ShowPopUpListener showpopupListener;

public QuickPopup(Context context, String text, int viewResource) {
mContext = context;
mWindow = new PopupWindow(context);
mWindowManager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
initCompo(viewResource);
}

public QuickPopup(Context context) {
this(context, "", R.layout.popup);
}

public QuickPopup(Context context, String text) {
this(context);
setText(text);
}

private void initCompo(int viewResource) {
LayoutInflater layoutInflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

setContentView(layoutInflater.inflate(viewResource, null));

txtShow = (TextView) mView.findViewById(R.id.text);
imgUp = (ImageView) mView.findViewById(R.id.arrow_up);
imgDown = (ImageView) mView.findViewById(R.id.arrow_down);

txtShow.setMovementMethod(ScrollingMovementMethod.getInstance());
txtShow.setSelected(true);
}

public void show(View anchor) {
preShow();

int[] location = new int[2];

anchor.getLocationOnScreen(location);

Rect anchorRect = new Rect(location[0], location[1], location[0]
+ anchor.getWidth(), location[1] + anchor.getHeight());

mView.measure(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);

int rootHeight = mView.getMeasuredHeight();
int rootWidth = mView.getMeasuredWidth();

final int screenWidth = mWindowManager.getDefaultDisplay().getWidth();
final int screenHeight = mWindowManager.getDefaultDisplay().getHeight();

int yPos = anchorRect.top - rootHeight;

boolean onTop = true;

if (anchorRect.top < screenHeight / 2) {
yPos = anchorRect.bottom;
onTop = false;
}

int whichArrow, requestedX;

whichArrow = ((onTop) ? R.id.arrow_down : R.id.arrow_up);
requestedX = anchorRect.centerX();

View arrow = whichArrow == R.id.arrow_up ? imgUp : imgDown;
View hideArrow = whichArrow == R.id.arrow_up ? imgDown : imgUp;

final int arrowWidth = arrow.getMeasuredWidth();

arrow.setVisibility(View.VISIBLE);

ViewGroup.MarginLayoutParams param = (ViewGroup.MarginLayoutParams) arrow
.getLayoutParams();

hideArrow.setVisibility(View.INVISIBLE);

int xPos = 0;

if (anchorRect.left + rootWidth > screenWidth) {
xPos = (screenWidth - rootWidth);// right click
} else if (anchorRect.left - (rootWidth / 2) < 0) {
xPos = anchorRect.left;// left clcik
} else {
xPos = (anchorRect.centerX() - (rootWidth / 2)); // inbetween
}

param.leftMargin = (requestedX - xPos) - (arrowWidth / 2);

if (onTop) {
txtShow.setMaxHeight(anchorRect.top - anchorRect.height());

} else {
txtShow.setMaxHeight(screenHeight - yPos);
}

mWindow.showAtLocation(anchor, Gravity.NO_GRAVITY, xPos, yPos);

mView.setAnimation(AnimationUtils.loadAnimation(mContext,
R.anim.float_anim));

}

protected void preShow() {
if (mView == null)
throw new IllegalStateException("view undefined");

if (showpopupListener != null) {
showpopupListener.onPreShow();
showpopupListener.onShow();
}

if (mBackgroundDrawable == null)
mWindow.setBackgroundDrawable(new BitmapDrawable());
else
mWindow.setBackgroundDrawable(mBackgroundDrawable);

mWindow.setWidth(WindowManager.LayoutParams.WRAP_CONTENT);
mWindow.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
mWindow.setTouchable(true);
mWindow.setFocusable(true);
mWindow.setOutsideTouchable(true);

mWindow.setContentView(mView);
}

public void setBackgroundDrawable(Drawable background) {
mBackgroundDrawable = background;
}

public void setContentView(View root) {
mView = root;

mWindow.setContentView(root);
}

public void setContentView(int layoutResID) {
LayoutInflater inflator = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

setContentView(inflator.inflate(layoutResID, null));
}

public void setOnDismissListener(PopupWindow.OnDismissListener listener) {
mWindow.setOnDismissListener(listener);
}

public void dismiss() {
mWindow.dismiss();
if (showpopupListener != null) {
showpopupListener.onDismiss();
}
}

public void setText(String text) {
txtShow.setText(text);
}

public void setShowListener(ShowPopUpListener showpopupListener) {
this.showpopupListener = showpopupListener;
}
}


Interface

public interface ShowPopUpListener {
void onPreShow();

void onDismiss();

void onShow();
}

res/anim/float_anim.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >

    <translate
        android:interpolator="@android:anim/bounce_interpolator"
        android:duration="1000"
        android:fillAfter="true"
        android:fromYDelta="0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:repeatCount="infinite"
        android:repeatMode="reverse"
        android:toYDelta="5%" />

</set>



Wednesday 25 September 2013

Video Recording in Background Using service Android

Here ,There is one Sample activity which records video in background using of service.

MainVideoActivity.class


public class MainVideoActivity extends Activity implements
SurfaceHolder.Callback {

public static SurfaceView mSurfaceView;
public static SurfaceHolder mSurfaceHolder;
public static Camera mCamera;
public static boolean mPreviewRunning;

@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_video);

mSurfaceView = (SurfaceView) findViewById(R.id.surfaceview);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
mSurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);

Button startVideoButton = (Button) findViewById(R.id.button1);
startVideoButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
startService(new Intent(MainVideoActivity.this,
RecorderService.class));
}
});

Button stopVideoButton = (Button) findViewById(R.id.button2);
stopVideoButton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
stopService(new Intent(MainVideoActivity.this,
RecorderService.class));
}
});
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
}

@Override
public void surfaceCreated(SurfaceHolder holder) {
}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
}


RecorderService.class (For start and stop  video recording )

public class RecorderService extends Service {
private SurfaceHolder mSurfaceHolder;
private static Camera camera;
public static boolean recordingStatus;
private MediaRecorder mediaRecorder;
private File directory;
private int cameraType = 0;

@Override
public void onCreate() {
recordingStatus = false;
camera = MainVideoActivity.mCamera;
mSurfaceHolder = MainVideoActivity.mSurfaceHolder;

super.onCreate();
}

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
if (recordingStatus == false) {

startRecording();
}

return START_STICKY;
}

@Override
public void onDestroy() {
stopRecording();
camera.release();
recordingStatus = false;

super.onDestroy();
}

@SuppressLint("NewApi")
public boolean startRecording() {
try {
recordingStatus = true;

camera = Camera.open(cameraType);
camera.setDisplayOrientation(90);
Camera.Parameters params = camera.getParameters();
camera.setParameters(params);
Camera.Parameters p = camera.getParameters();

camera.setParameters(p);

camera.unlock();

mediaRecorder = new MediaRecorder();
mediaRecorder.setCamera(camera);
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.DEFAULT);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.DEFAULT);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);

directory = new File(Environment.getExternalStorageDirectory()
.toString() + "/videodemo/");
if (!directory.exists())
directory.mkdirs();

long currentTime = System.currentTimeMillis();

String uniqueOutFile = Environment.getExternalStorageDirectory()
.toString()
+ "/videodemo/videooutput"
+ currentTime
+ ".mp4";
File outFile = new File(directory, uniqueOutFile);
if (outFile.exists()) {
outFile.delete();
}

mediaRecorder.setOutputFile(uniqueOutFile);

mediaRecorder.setVideoSize(350, 250);
mediaRecorder.setPreviewDisplay(mSurfaceHolder.getSurface());
mediaRecorder.setOrientationHint(90);

mediaRecorder.prepare();
mediaRecorder.start();

return true;
} catch (IllegalStateException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}

// Stop service
public void stopRecording() {
mediaRecorder.stop();
mediaRecorder.release();
}
}

Add below permission in manifest file.

<uses-permission android:name="android.permission.CAMERA" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.RECORD_VIDEO" />
    <uses-permission android:name="android.permission.RECORD_AUDIO" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <uses-feature android:name="android.hardware.camera" />
    <uses-feature android:name="android.hardware.camera.autofocus" />

define service.
 <service android:name="com.videodemo.RecorderService" />

Wednesday 18 September 2013

Facebook like photo viewer in android

       Here,In this blog I tried to open full screen image with some nice animations and transitions, much like the new Facebook app provides.

As shown below zoomImageFromThumb function image will be open in full size with animation.
android:minSdkVersion="14"

private void zoomImageFromThumb(final View thumbView, int imageResId) {
// If there's an animation in progress, cancel it immediately and
// proceed with this one.
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}

// Imageview define in xml for full screen.
final ImageView expandedImageView = (ImageView) findViewById(R.id.expanded_image);
expandedImageView.setImageResource(imageResId);

// Calculate the starting and ending bounds for the zoomed-in image.
// This step
// involves lots of math. Yay, math.
final Rect startBounds = new Rect();
final Rect finalBounds = new Rect();
final Point globalOffset = new Point();

// R.id.container layout main view id.

thumbView.getGlobalVisibleRect(startBounds);
findViewById(R.id.container).getGlobalVisibleRect(finalBounds,
globalOffset);
startBounds.offset(-globalOffset.x, -globalOffset.y);
finalBounds.offset(-globalOffset.x, -globalOffset.y);

// Adjust the start bounds to be the same aspect ratio as the final
// bounds using the
// "center crop" technique. This prevents undesirable stretching during
// the animation.
// Also calculate the start scaling factor (the end scaling factor is
// always 1.0).
float startScale;
if ((float) finalBounds.width() / finalBounds.height() > (float) startBounds
.width() / startBounds.height()) {
// Extend start bounds horizontally
startScale = (float) startBounds.height() / finalBounds.height();
float startWidth = startScale * finalBounds.width();
float deltaWidth = (startWidth - startBounds.width()) / 2;
startBounds.left -= deltaWidth;
startBounds.right += deltaWidth;
} else {
// Extend start bounds vertically
startScale = (float) startBounds.width() / finalBounds.width();
float startHeight = startScale * finalBounds.height();
float deltaHeight = (startHeight - startBounds.height()) / 2;
startBounds.top -= deltaHeight;
startBounds.bottom += deltaHeight;
}

// Hide the thumbnail and show the zoomed-in view. When the animation
// begins,
// it will position the zoomed-in view in the place of the thumbnail.
thumbView.setAlpha(0f);
expandedImageView.setVisibility(View.VISIBLE);

// Set the pivot point for SCALE_X and SCALE_Y transformations to the
// top-left corner of
// the zoomed-in view (the default is the center of the view).
expandedImageView.setPivotX(0f);
expandedImageView.setPivotY(0f);

// Construct and run the parallel animation of the four translation and
// scale properties
// (X, Y, SCALE_X, and SCALE_Y).
AnimatorSet set = new AnimatorSet();
set.play(
ObjectAnimator.ofFloat(expandedImageView, View.X,
startBounds.left, finalBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
startBounds.top, finalBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_X,
startScale, 1f))
.with(ObjectAnimator.ofFloat(expandedImageView, View.SCALE_Y,
startScale, 1f));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
mCurrentAnimator = null;
}

@Override
public void onAnimationCancel(Animator animation) {
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;

// Upon clicking the zoomed-in image, it should zoom back down to the
// original bounds
// and show the thumbnail instead of the expanded image.
final float startScaleFinal = startScale;
expandedImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mCurrentAnimator != null) {
mCurrentAnimator.cancel();
}

// Animate the four positioning/sizing properties in parallel,
// back to their
// original values.
AnimatorSet set = new AnimatorSet();
set.play(
ObjectAnimator.ofFloat(expandedImageView, View.X,
startBounds.left))
.with(ObjectAnimator.ofFloat(expandedImageView, View.Y,
startBounds.top))
.with(ObjectAnimator.ofFloat(expandedImageView,
View.SCALE_X, startScaleFinal))
.with(ObjectAnimator.ofFloat(expandedImageView,
View.SCALE_Y, startScaleFinal));
set.setDuration(mShortAnimationDuration);
set.setInterpolator(new DecelerateInterpolator());
set.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}

@Override
public void onAnimationCancel(Animator animation) {
thumbView.setAlpha(1f);
expandedImageView.setVisibility(View.GONE);
mCurrentAnimator = null;
}
});
set.start();
mCurrentAnimator = set;
}
});
}




How to use this function?
Here i am using this function on listview item click to open image in full screen with Animation (much like the new Facebook app provides).

listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
                               // R.drawable.image2 = full image.
zoomImageFromThumb(arg1, R.drawable.image2);
}
});

Wednesday 26 June 2013

Image with Zoom in-out and draw paint on zoomed image using canvas in Android.


    Here,I used canvas in order to zoom image view with image including using setImageMatrix(). As shown below class use for zoom and paint. In entire screen became to zoom in/out then when i click on zoom button i pass one Boolean as false which stop zooming and draw line on touch of finger.

    PaintView class is used for draw line on zoomed image for perticuler position of image-view. 
imageView.setOnTouchListener(new OnTouchListener()) is used for zoom in-out of image bitmap.
combineImages() function used for merge both image and paint bitmap.


public class PaintScreen extends Activity {

Context mContext;
private Paint mPaint;
MaskFilter mEmboss;
MaskFilter mBlur;
private LinearLayout mPaintBaseLayout, mPaintBaseLayout2;
private PaintView mPaintView;

// These matrices will be used to move and zoom image
Matrix matrix = new Matrix();
Matrix matrix1 = new Matrix();
Matrix savedMatrix = new Matrix();
Matrix savedMatrix2 = new Matrix();
Matrix dmMtrx = new Matrix();

private int WIDTH = 0;
private int HEIGHT = 1;

// We can be in one of these 3 states
static final int NONE = 0;
static final int DRAG = 1;
static final int POINT2 = 2;
static final int ZOOM = 3;
int mode = NONE;
private static final float MIN_ZOOM = 0.0f;
private static final float MAX_ZOOM = 1.0f;


// Remember some things for zooming
PointF start = new PointF();
PointF mid = new PointF();
float oldDist = 1f;
float newDist;
float distanceOffset = 50f;
float minOffset = 50f;
float maxOffset = 10000f;
private boolean falg = true;
private int startval = 0;
Bitmap newbm;
private float finalscale;
Bitmap bm;
private float scaledImageOffsetX;
private float scaledImageOffsetY;
ImageView imageView;
ProgressDialog dialog;
private float[] matrixValues;
Bitmap temp;

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

this.initialize();

this.PaintSet();
imageView = (ImageView) findViewById(R.id.imageview1);
Button button = (Button) findViewById(R.id.btnzoom);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (falg) {
getFlag(false);
} else {
getFlag(true);
}
}
});

Button btnset = (Button) findViewById(R.id.btnset);
btnset.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
startval = 1;
mPaintBaseLayout.setDrawingCacheEnabled(true);

imageView.setVisibility(View.VISIBLE);

mPaintBaseLayout.setVisibility(View.GONE);
new SaveImageAsynk().execute();
}
});

imageView.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
ImageView view = (ImageView) v;

switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
savedMatrix.set(matrix1);
start.set(event.getX(), event.getY());
mode = DRAG;
break;
case MotionEvent.ACTION_POINTER_DOWN:
oldDist = spacing(event);
if (oldDist > 10f) {
start.set(event.getX(), event.getY());
savedMatrix.set(matrix1);
midPoint(mid, event);
// mode = POINT2;
mode = ZOOM;
}
break;
case MotionEvent.ACTION_UP:
mode = NONE;
distanceOffset = minOffset;
case MotionEvent.ACTION_POINTER_UP:
mode = NONE;
distanceOffset = minOffset;
break;
case MotionEvent.ACTION_MOVE:
if (mode == POINT2) {
newDist = spacing(event);
if (newDist - oldDist > 5f
|| newDist - oldDist < -5f) {
mode = ZOOM;
} else {
start.set(event.getX(), event.getY());
mode = DRAG;
}
} else if (mode == DRAG) {
matrix1.set(savedMatrix);
matrix1.postTranslate(event.getX() - start.x,
event.getY() - start.y);
} else if (mode == ZOOM) {
newDist = spacing(event);
if (newDist > 10f) {
matrix1.set(savedMatrix);
float scale = newDist / oldDist;
matrix1.postScale(scale, scale, mid.x,
mid.y);
finalscale = scale;
}
}
break;
}

view.setImageMatrix(matrix1);
// matrixTurning(matrix1, view);
return true; // indicate event was handled
}
});
}

class SaveImageAsynk extends AsyncTask<String, String, String>{
Bitmap tempBm;
@Override
protected String doInBackground(String... params) {
temp = Bitmap.createBitmap(bm, 0, 0, bm.getWidth(), bm.getHeight(), matrix, false);
newbm = Bitmap.createBitmap(mPaintBaseLayout.getWidth(),
mPaintBaseLayout.getHeight(), Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(newbm);
mPaintBaseLayout.draw(canvas);
tempBm = combineImages(newbm, temp);
if (newbm != null) {
newbm = null;
}
if (temp != null) {
temp = null;
}
return null;
}

@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
imageView.setImageBitmap(tempBm);
try {
dialog.dismiss();
if (dialog != null) {
dialog = null;
}
} catch (Exception e) {
}
}

@Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(PaintScreen.this);
dialog.setMessage("Loading...");
dialog.show();
}

}
public Bitmap combineImages(Bitmap c, Bitmap s) {
Bitmap cs = null;

int width, height = 0;

if (c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}
Log.e("hw :", "X = "+width + " Y = "+height);
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);

Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(s,new Matrix(), null);
comboImage.drawBitmap(c,Math.abs(scaledImageOffsetX),Math.abs(scaledImageOffsetY), null);

return cs;
}

private void initialize() {
mPaintBaseLayout = (LinearLayout) findViewById(R.id.paint_paint_base_layout);
mPaintBaseLayout2 = (LinearLayout) findViewById(R.id.paint_paint_base_layout2);

mContext = this;
mPaint = new Paint();
mPaintView = new PaintView(mContext);
mPaintView.setBackgroundColor(Color.TRANSPARENT);
mPaintBaseLayout.addView(mPaintView, new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
mPaintBaseLayout.setBackgroundColor(Color.TRANSPARENT);

// mPaintView.setScaleType(ScaleType.FIT_XY);
mPaintView.setAdjustViewBounds(true);
mPaintView.setMPaint(mPaint);
bm = BitmapFactory.decodeResource(getResources(), R.drawable.nat);

mPaintView.setImageBitmap(bm);

mPaintView.setOnTouchListener(new OnTouchListener() {

@Override
public boolean onTouch(View v, MotionEvent event) {
PaintView view = (PaintView) v;
view.setScaleType(ImageView.ScaleType.MATRIX);
switch (event.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
if (falg) {
savedMatrix.set(matrix);
start.set(event.getX(), event.getY());
mode = DRAG;
} else {
view.onTouchEvent(event);
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
if (falg) {
oldDist = spacing(event);
if (oldDist > 10f) {
start.set(event.getX(), event.getY());
savedMatrix.set(matrix);
midPoint(mid, event);
mode = ZOOM;
}
}
break;
case MotionEvent.ACTION_UP:
if (falg) {
mode = NONE;
distanceOffset = minOffset;
}
case MotionEvent.ACTION_POINTER_UP:
if (falg) {
mode = NONE;
distanceOffset = minOffset;
}
break;
case MotionEvent.ACTION_MOVE:
if (falg) {
if (mode == POINT2) {
newDist = spacing(event);
if (newDist - oldDist > 5f
|| newDist - oldDist < -5f) {
mode = ZOOM;
} else {
start.set(event.getX(), event.getY());
mode = DRAG;
}
} else if (mode == DRAG) {
matrix.set(savedMatrix);
matrix.postTranslate(event.getX() - start.x,
event.getY() - start.y);
} else if (mode == ZOOM) {
newDist = spacing(event);
if (newDist > 10f) {
matrix.set(savedMatrix);
float scale = newDist / oldDist;
matrix.postScale(scale, scale, mid.x, mid.y);
finalscale = scale;
}
}
} else {
view.onTouchEvent(event);
}
break;
}

limitZoom(matrix);
view.setImageMatrix(matrix);

matrixTurning(matrix, view);
RectF r = new RectF();
matrix.mapRect(r);
scaledImageOffsetX = r.left;
scaledImageOffsetY = r.top;

return true;
}
});
}


private void limitZoom(Matrix m) {

        float[] values = new float[9];
        m.getValues(values);
        float scaleX = values[Matrix.MSCALE_X];
        float scaleY = values[Matrix.MSCALE_Y];
        if(scaleX > MAX_ZOOM) {
            scaleX = MAX_ZOOM;
        } else if(scaleX < MIN_ZOOM) {
            scaleX = MIN_ZOOM;
        }

        if(scaleY > MAX_ZOOM) {
            scaleY = MAX_ZOOM;
        } else if(scaleY < MIN_ZOOM) {
            scaleY = MIN_ZOOM;
        }

        values[Matrix.MSCALE_X] = scaleX;
        values[Matrix.MSCALE_Y] = scaleY;
        m.setValues(values);
    }

public boolean getFlag(boolean b) {
return falg = b;
}

/** Determine the space between the first two fingers */
private static float spacing(MotionEvent event) {
float x = event.getX(0) - event.getX(1);
float y = event.getY(0) - event.getY(1);
return FloatMath.sqrt(x * x + y * y);
}

/** Calculate the mid point of the first two fingers */
private static void midPoint(PointF point, MotionEvent event) {
float x = event.getX(0) + event.getX(1);
float y = event.getY(0) + event.getY(1);
point.set(x / 2, y / 2);
}

private void matrixTurning(Matrix matrix, ImageView view) {

float[] value = new float[9];
matrix.getValues(value);
float[] savedValue = new float[9];
savedMatrix2.getValues(savedValue);

// view size
int width = view.getWidth();
int height = view.getHeight();

// image size
Drawable d = view.getDrawable();
if (d == null)
return;
int imageWidth = d.getIntrinsicWidth();
int imageHeight = d.getIntrinsicHeight();
int scaleWidth = (int) (imageWidth * value[0]);
int scaleHeight = (int) (imageHeight * value[0]);

if (value[2] < width - scaleWidth)
value[2] = width - scaleWidth;
if (value[5] < height - scaleHeight)
value[5] = height - scaleHeight;
if (value[2] > 0)
value[2] = 0;
if (value[5] > 0)
value[5] = 0;

if (value[0] > 10 || value[4] > 10) {
value[0] = savedValue[0];
value[4] = savedValue[4];
value[2] = savedValue[2];
value[5] = savedValue[5];
}

if (imageWidth > width || imageHeight > height) {

if (scaleWidth < width && scaleHeight < height) {
int target = WIDTH;

if (imageWidth < imageHeight)
target = HEIGHT;

if (target == WIDTH)
value[0] = value[4] = (float) width / imageWidth;
if (target == HEIGHT)
value[0] = value[4] = (float) height / imageHeight;

scaleWidth = (int) (imageWidth * value[0]);
scaleHeight = (int) (imageHeight * value[4]);

if (scaleWidth == width)
value[0] = value[4] = (float) width / imageWidth;
if (scaleHeight == height)
value[0] = value[4] = (float) height / imageHeight;
}

} else {
if (value[0] < 1)
value[0] = 1;
if (value[4] < 1)
value[4] = 1;
}

scaleWidth = (int) (imageWidth * value[0]);
scaleHeight = (int) (imageHeight * value[4]);

if (scaleWidth < width) {
value[2] = (float) width / 2 - (float) scaleWidth / 2;
}
if (scaleHeight < height) {
value[5] = (float) height / 2 - (float) scaleHeight / 2;
}

matrix.setValues(value);
savedMatrix2.set(matrix);

}

public void PaintSet() {

mPaint.setAntiAlias(true);
mPaint.setDither(true);
mPaint.setColor(0xFFFF0000);
mPaint.setStyle(Paint.Style.STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(10);

// getWindowManager().getDefaultDisplay().getMetrics(mDisplayMetrics);
mEmboss = new EmbossMaskFilter(new float[] { 1, 1, 1 }, 0.4f, 6, 3.5f);
mBlur = new BlurMaskFilter(24, BlurMaskFilter.Blur.NORMAL);
}

public void colorChanged(int color) {
mPaint.setColor(color);
}

}

class PaintView extends ImageView {

private Bitmap mBitmap;
private Canvas mCanvas;
private Path mPath;
private Paint mBitmapPaint;

// onDraw
private Paint mPaint;

// onTouch
private float mX, mY;
private static final float TOUCH_TOLERANCE = 4;

public PaintView(Context context) {
this(context, null);
}

public PaintView(Context context, AttributeSet attrs) {
super(context, attrs);

mBitmap = Bitmap.createBitmap(1024, 1024, Bitmap.Config.ARGB_8888);
mPath = new Path();
mBitmapPaint = new Paint(Paint.DITHER_FLAG);

}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
}

@Override
protected void onDraw(Canvas canvas) {
// canvas.drawColor(0xFFAAAAAA);
super.onDraw(canvas);
mCanvas = canvas;
// canvas = mCanvas;
canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
// canvas.drawBitmap(mBitmap, PaintScreen.matrix, mBitmapPaint);
canvas.drawPath(mPath, mPaint);

}

public void clear() {
mPaint.reset();
// invalidate();
}

public void setMPaint(Paint paint) {
mPaint = paint;
}

private void touchStart(float x, float y) {
// mPath.reset();
mPath.moveTo(x, y);
mX = x;
mY = y;
}

private void touchMove(float x, float y) {
float dx = Math.abs(x - mX);
float dy = Math.abs(y - mY);
if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
mX = x;
mY = y;
}
}

private void touchUp() {
mPath.lineTo(mX, mY);
// commit the path to our offscreen
mCanvas.drawPath(mPath, mPaint);
// kill this so we don't double draw
mPath.reset();
}

@Override
public boolean onTouchEvent(MotionEvent event) {
float x = event.getX();
float y = event.getY();

Log.d("PaintView", "ev ->" + event.getAction());

switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
touchStart(x, y);
invalidate();
break;
case MotionEvent.ACTION_MOVE:
touchMove(x, y);
invalidate();
break;
case MotionEvent.ACTION_UP:
touchUp();
invalidate();
break;
}
return true;
}

public void cMatrix(Matrix matrix) {
mCanvas.setMatrix(matrix);
}
}

XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mainrel"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    tools:context=".ImageMainActivity" >

    <Button
        android:id="@+id/btnzoom"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Zoom" />

    <Button
        android:id="@+id/btnset"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_toRightOf="@+id/btnzoom"
        android:text="Done" />

    <ImageView
        android:id="@+id/imageview1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_below="@+id/btnzoom"
        android:scaleType="matrix"
        android:visibility="gone" />

    <LinearLayout
        android:id="@+id/paint_paint_base_layout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnzoom"
        android:orientation="horizontal" />

    <LinearLayout
        android:id="@+id/paint_paint_base_layout2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/btnzoom"
        android:orientation="horizontal"
        android:visibility="gone" />

</RelativeLayout>

Copy and share your useful data from Google chrome browser to your application in android.

Here In this blog I explain that how to copy and share your useful data from chrome browser in android. 1) How to show your applic...