Image translation, scaling, rotation and _android based on Android

Source: Internet
Author: User
Tags gety stub touch eventbus

Objective

Previously because of the project requirements, which use to the picture of the click Display cancellation, the image translation zoom function, yesterday suddenly want to add the image of the rotation function, on the internet to see a lot of relevant examples, but did not see that can achieve the same function I want.

Demand:

(1) Picture translation, scaling, rotation, etc. after a series of operations, the picture needs to be automatically centered display.

(2) Automatic horizontal display or vertical display of picture after rotation

(3) The image can be rotated while zooming in and out

Demo to achieve part of the effect of screenshots

Demo Main code

Java

Mainactivity.java package Com.practice.noyet.rotatezoomimageview;
Import android.app.Activity;
Import Android.graphics.Bitmap;
Import Android.graphics.BitmapFactory;
Import Android.graphics.Matrix;
Import Android.graphics.PointF;
Import Android.graphics.RectF;
Import Android.os.AsyncTask;
Import Android.os.Bundle;
Import Android.util.DisplayMetrics;
Import android.view.MotionEvent;
Import Android.view.View;
Import Android.widget.ImageView;
Import Com.ypy.eventbus.EventBus;
Import Java.io.File;
Import Java.math.BigDecimal;
/** * Package:com.practice.noyet.rotatezoomimageview * Created by Noyet on 2015/11/11.
  * * Public class Mainactivity extends activity implements View.ontouchlistener {private ImageView mimageview;
  Private PointF point0 = new PointF ();
  Private PointF Pointm = new PointF ();
  Private final int NONE = 0;
  /** * Translation/private final int DRAG = 1;
  /** * rotate, zoom/private final int ZOOM = 2;
  /** * Set event mode/private int mode = NONE;
 /**  * Image zoom matrix/private Matrix Matrix = new Matrix ();
  /** * Save Touch Image Zoom Matrix * * * Private Matrix Savedmatrix = new Matrix ();
  /** * Save the image scaling matrix in the contact movement process * * * Private matrix matrix1 = new Matrix ();
  /** * Screen Height * * private int displayheight;
  /** * Screen width */private int displaywidth;
  /** * Minimum scaling ratio/protected float Minscale = 1f;
  /** * Maximum scaling ratio * * protected float Maxscale = 3f;
  /** * Current ZOOM ratio * * Protected float Currentscale = 1f;
  /** * Multi-point Touch 2 touch points between the starting distance * * Private float olddist;
  /** * Multi-point touch when the picture's starting angle * * Private float oldrotation = 0;
  /** * Rotary Angle * * Protected float rotation = 0;
  /** * Picture Initial width * * * private int imgwidth;
  /** * Picture Initial height * * private int imgheight;
  /** * Set single point touch exit picture Display, single point touch sensitivity (can be set for different mobile phone alone) * * Protected final int move_max = 2;
  /** * Single point touch when the finger trigger ' motionevent.action_move ' times * private int fingernummove = 0;
  Private Bitmap BM; /** * Save Matrix ZOOM ratio * * Private float MAtrixscale= 1; /*private String imagepath;*//** * Displays the network picture being cached in * * @param event Observer events/public void Oneventmainthread (
    Customeventbus event) {if (event = = null) {return;
      } if (Event.type = = CustomEventBus.EventType.SHOW_PICTURE) {BM = (Bitmap) event.obj;
    ShowImage ();
    } @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
    Setcontentview (R.layout.activity_main);
  InitData (); public void InitData () {//TODO auto-generated method Stub bm = Bitmapfactory.decoderesource (Getresources (),
    R.drawable.alipay);
    Displaymetrics DM = getresources (). Getdisplaymetrics ();
    Displaywidth = Dm.widthpixels;
    Displayheight = Dm.heightpixels;
    Mimageview = (ImageView) Findviewbyid (R.id.image_view);
    Mimageview.setontouchlistener (this);
    ShowImage (); When displaying network pictures, use/*file File = Mainapplication.getinstance (). Getimagecache (). Getdiskcache (). Get (Picture path);
    if (!file.exists ()) {Toast.maketext (this, "Picture path error", Toast.length_short). Show ();
    else {new MyTask (). Execute (file);
    }*/} @Override Public boolean Ontouch (view view, Motionevent event) {ImageView ImageView = (imageview) view; Switch (event.getaction () & Motionevent.action_mask) {Case MotionEvent.ACTION_DOWN:savedMatrix.set (
        Matrix);
        Point0.set (Event.getx (), event.gety ());
        mode = DRAG;
        System.out.println ("Motionevent--action_down");
      Break
        Case MotionEvent.ACTION_POINTER_DOWN:oldDist = spacing (event);
        Oldrotation = Rotation (event);
        Savedmatrix.set (matrix);
        Setmidpoint (Pointm, event);
        mode = ZOOM;
        System.out.println ("Motionevent--action_pointer_down---" + oldrotation);
      Break
        Case MotionEvent.ACTION_UP:if (Mode = = DRAG & (Fingernummove this.finish ();
        } checkview ();
  Centerandrotate ();      Imageview.setimagematrix (matrix);
        System.out.println ("motionevent--action_up");
        Fingernummove = 0;
      Break
        Case MotionEvent.ACTION_POINTER_UP:mode = NONE;
        System.out.println ("motionevent--action_pointer_up");
      Break
        Case MotionEvent.ACTION_MOVE:operateMove (event);
        Imageview.setimagematrix (MATRIX1);
        fingernummove++;
        System.out.println ("Motionevent--action_move");
    Break
  return true;
    @Override protected void OnDestroy () {//TODO auto-generated Method Stub Super.ondestroy ();
   if (BM!= null &!bm.isrecycled ()) {bm.recycle ();////Reclaim the memory of the picture System.GC ();//Remind the system to recycle}}/**
    * Show Picture */private void ShowImage () {imgwidth = Bm.getwidth ();
    ImgHeight = Bm.getheight ();
    Mimageview.setimagebitmap (BM);
    Matrix.setscale (1, 1);
    Centerandrotate ();
  Mimageview.setimagematrix (matrix); /** * operation when the contact moves * @param event Touch Events/private void Operatemove (Motionevent event) {Matrix1.set (Savedmatrix);
        Switch (mode) {case DRAG:matrix1.postTranslate (Event.getx ()-point0.x, Event.gety ()-POINT0.Y);
      Break
        Case zoom:rotation = Rotation (event)-oldrotation;
        float newdist = spacing (event);
        float scale = newdist/olddist; Currentscale = (Scale > 3.5f)?
        3.5f:scale;
        SYSTEM.OUT.PRINTLN ("Zoom Multiple---" + currentscale);
        System.out.println ("Rotation angle---" + rotation);
        /** * * Matrix1.postscale (Currentscale, Currentscale, pointm.x, POINTM.Y);
        /** spin/matrix1.postrotate (rotation, DISPLAYWIDTH/2, DISPLAYHEIGHT/2);
    Break 
    }/** * Two contact distance * * @param event Touch Events * @return Float */private float spacing (motionevent event) {
    float x = event.getx (0)-event.getx (1);
    Float y = event.gety (0)-event.gety (1); return (float) math.sqrt (x * x +Y * y); /** * Get rotation angle * * Private float rotation (Motionevent event) {Double delta_x = (event.getx (0)-Event.getx (1
    ));
    Double delta_y = (event.gety (0)-event.gety (1));
    Double radians = math.atan2 (delta_y, delta_x);
  return (float) math.todegrees (radians);  /** * Two Contact center coordinates * * @param POINTM Intermediate coordinates * @param event touch events/private void Setmidpoint (PointF Pointm,
    Motionevent event) {float x = event.getx (0) + event.gety (1);
    Float y = event.gety (0) + event.gety (1);
  Pointm.set (X/2, Y/2); /** * CHECK constraints (zoom multiples)/private void Checkview () {if (Currentscale > 1) {if (Currentscale * Matri
        XScale > Maxscale) {matrix.postscale (Maxscale/matrixscale, Maxscale/matrixscale, pointm.x, POINTM.Y);
      Matrixscale = Maxscale;
        else {Matrix.postscale (Currentscale, Currentscale, pointm.x, POINTM.Y);
      Matrixscale *= Currentscale; } else {if (Currentscale * matRixscale else {Matrix.postscale (Currentscale, Currentscale, pointm.x, POINTM.Y);
      Matrixscale *= Currentscale; /** * Picture centered, judging rotation angle is less than (45 * x +) degree of rotation (x) degree is greater than the rotation ((x+1))/private void Centerandrotate (
    {RECTF rect = new RECTF (0, 0, ImgWidth, imgheight);
    Matrix.maprect (rect);
    Float width = rect.width ();
    float height = rect.height ();
    float dx = 0;
    float dy = 0;
    if (width 2-width/2-rect.left;
    else if (Rect.left > 0) {dx =-rect.left;
    else if (rect.right if (height 2-HEIGHT/2-rect.top);
    else if (Rect.top > 0) {dy =-rect.top;
      else if (rect.bottom if (rotation!= 0) {int rotationnum = (int) (ROTATION/90);
      float Rotationavai = new BigDecimal (rotation%). Setscale (1, bigdecimal.round_half_up). Floatvalue ();
      float realrotation = 0; if (Rotation > 0) {realrotation = Rotationavai > 45? (Rotationnum + 1) * 90:rotatIonnum * 90; else if (rotation 0) {realrotation = Rotationavai 45?
      (rotationNum-1) * 90:rotationnum * 90;
      } System.out.println ("realrotation:" + realrotation);
      Matrix.postrotate (Realrotation, DISPLAYWIDTH/2, DISPLAYHEIGHT/2);
    rotation = 0;
    }/** * Displays the network picture when using/private class MyTask extends Asynctaskfile, File, bitmap> {Bitmap Bitmap;
    String path;
    int scale = 1;
    Long size;
        @Override protected Bitmap doinbackground (File ... params) {//TODO auto-generated method stub try {
        Size = Params[0].length ();
        Path = Params[0].getabsolutepath ();
        Bitmapfactory.options Options = new Bitmapfactory.options ();
        Options.injustdecodebounds = true;
        Bitmapfactory.decodefile (path, options);
        Scale = calculateinsamplesize (options, Displaywidth, displayheight);
        Options.injustdecodebounds = false;
     Options.insamplesize = scale;   Bitmap = bitmapfactory.decodefile (path, options);
      catch (Exception e) {//TODO auto-generated catch block E.printstacktrace ();
    return bitmap; @Override protected void OnPostExecute (Bitmap result) {//TODO auto-generated the method stub Eventbus.
    Getdefault (). Post (new Customeventbus (CustomEventBus.EventType.SHOW_PICTURE, result));
     /** * Get Picture Scaling * * @param paramoptions Options * @param paramInt1 Width * @param paramInt2 high
                     * @return int */private int calculateinsamplesize (Bitmapfactory.options paramoptions,
      int paramInt1, int paramInt2) {int i = paramoptions.outheight;
      int j = Paramoptions.outwidth;
      int k = 1; if ((i > ParamInt2) | | (J > ParamInt1))
        {int m = Math.Round (I/paramint2);
        int n = math.round (j/paramint1);
    K = m return k; }} Customeventbus.java Package Com.practice.noyeT.rotatezoomimageview;
/** * Package:com.practice.noyet.rotatezoomimageview * Created by Noyet on 2015/11/11.
  * * Public class Customeventbus {public eventtype type;
  public Object obj;
    Public Customeventbus (eventtype type, Object obj) {this.type = type;
  This.obj = obj; Enum EventType {Show_picture}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.