Wednesday, June 6, 2012

[Android] pinch zoom event with font size change

Android Java code for the pinch zoom event that makes increase font size.

import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;

public class Introduce extends Activity implements OnTouchListener{
 final static float STEP = 200;
 TextView mtxtRatio1,mtxtRatio2,mtxtRatio3,mtxtRatio4;
 float mRatio = 1.0f;
 int mBaseDist;
 float mBaseRatio;
 float fontsize = 13;

 public void onCreate(Bundle savedInstanceState) {
  mtxtRatio1 = (TextView)findViewById(;

 public boolean onTouchEvent(MotionEvent event) {
  if (event.getPointerCount() == 2) {
   int action = event.getAction();
   int pureaction = action & MotionEvent.ACTION_MASK;
   if (pureaction == MotionEvent.ACTION_POINTER_DOWN) {
    mBaseDist = getDistance(event);
    mBaseRatio = mRatio;
   } else {
    float delta = (getDistance(event) - mBaseDist) / STEP;
    float multi = (float)Math.pow(2, delta);
    mRatio = Math.min(1024.0f, Math.max(0.1f, mBaseRatio * multi));
  return true; 

 int getDistance(MotionEvent event) {
  int dx = (int)(event.getX(0) - event.getX(1));
  int dy = (int)(event.getY(0) - event.getY(1));
  return (int)(Math.sqrt(dx * dx + dy * dy));

 public boolean onTouch(View v, MotionEvent event) {
  // TODO Auto-generated method stub
  return false;


Josue Montano said...

Thanks! just what I was looking for

Daniel Scholtus said...

Byung Yong Park this is great, could you explain a little how to wire it up?

Jeet Dholakia said...
This comment has been removed by the author.
Anonymous said...

Thank you so much,very useful!

Anonymous said...

thank you so much,its really helpful!

Anonymous said...

if the textview is in a scrollview , then it dont zoom rather it scroll . how can i solve this ??

syed said...

ya its very good ..but i need to stop in an certain limit in zoom in and out so the text will be readable

for IT the said...

I have read your blog its very attractive and impressive. I like it your blog.

Java Training in Chennai Core Java Training in Chennai Core Java Training in Chennai

Java Online Training Java Online Training Core Java 8 Training in Chennai Core java 8 online training JavaEE Training in Chennai Java EE Training in Chennai