欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android单点触控实现图片平移、缩放、旋转功能

程序员文章站 2024-02-20 23:25:52
相信大家使用多点对图片进行缩放,平移的操作很熟悉了,大部分大图的浏览都具有此功能,有些app还可以对图片进行旋转操作,qq的大图浏览就可以对图片进行旋转操作,大家都知道对图...

相信大家使用多点对图片进行缩放,平移的操作很熟悉了,大部分大图的浏览都具有此功能,有些app还可以对图片进行旋转操作,qq的大图浏览就可以对图片进行旋转操作,大家都知道对图片进行缩放,平移,旋转等操作可以使用matrix来实现,matrix就是一个3x3的矩阵,对图片的处理可分为四个基础变换操作,translate(平移变换)、rotate(旋转变换)、scale (缩放变换)、skew(错切变换),如果大家对matrix不太了解的话可以看看这篇文章(点击查看),作者对每一种matrix的变换写的很清楚,但是如果使用一个手指对图片进行缩放,平移,旋转等操作大家是否了解呢,其实单手指操作跟多手指操作差不多,当然也是使用matrix来实现的,无非是在缩放比例和旋转角度的计算上面有些不一样,也许你会有疑问,多点操作图片缩放旋转是两个手指操作,平移的时候是一个手指操作,那么你单手在图片即平移,又缩放旋转难道不会有冲突吗?是的,这样子肯定是不行的,我们必须将平移和缩放旋转进行分开。如下图

Android单点触控实现图片平移、缩放、旋转功能

图片外面的框是一个边框,如果我们手指触摸的是上面的蓝色小图标我们就对其进行缩放旋转操作,如果是触摸到其他的区域我们就对其进行平移操作,这样就避免了上面所说的冲突问题,这里对图片的平移操作并没有使用matrix来实现,而是使用layout()方法来对其进行位置的变换。

Android单点触控实现图片平移、缩放、旋转功能

计算缩放比例比较简单,使用手指移动的点到图片所在中心点的距离除以图片对角线的一半就是缩放比例了,接下来就计算旋转角度,如下图

Android单点触控实现图片平移、缩放、旋转功能

premove是手指移动前一个点,curmove就是当前手指所在的点,还有一个中心点center,知道三个点求旋转的夹角是不是很简单呢,就是线段a和线段c的一个夹角,假设夹角为o,  o的余弦值 cos o = (a * a + c * c - b * b) / (2 * a * c), 知道余弦值夹角就出来了,但是这里还有一个问题,我们在使用matrix对图片进行旋转的时候需要区别顺时针旋转还是逆时针旋转,顺时针旋转角度为正,所以上面我们只求出了旋转的角度,并不知道是顺时针还是逆时针。

具体怎么求是顺时针角度还是逆时针角度呢?有些同学可能会根据curmove和promove的x ,y 的大小来判断,比如上面的图中,如果curmove.x > promove.x则为顺时针,否则为逆时针,这当然是一种办法,可是你想过这种方法只适合在第二象限,在第一,第三,第四象限这样子判断就不行了,当然你可以判断当前的点在第几象限,然后在不同的象限采用不同的判断,这样子判断起来会很复杂。

有没有更加简单的方法来判断呢?答案是肯定的,我们可以使用数学中的向量叉乘来判断。假如向量a(x1, y1)和向量b(x2, y2),我们可以使用向量叉乘 |a x b| = x1*y2 - x2*y1 = |a|×|b|×sin(向量a到b的夹角), 所以这个值的正负也就是a到b旋转角sin值的正负, 顺时针旋转角度0~180,sin>0, 顺时针旋转角度180~360或者说逆时针旋转0~180,sin<0, 所以我们可以用个center到promove的向量 叉乘 center到curmove的向量来判断是顺时针旋转还是逆时针旋转。

接下来我们就开始动手实现此功能,我们采用一个自定义的view来实现,这里就叫singletouchview,直接继承view, 从上面的图中我们可以定义出一些自定义的属性,比如用于缩放的图片,控制缩放旋转的小图标,图片边框的颜色等,我定义了如下的属性

<declare-styleable name="singletouchview"> 
  <attr name="src" format="reference" />      <!-- 用于缩放旋转的图标 --> 
  <attr name="editable" format="boolean"/>     <!-- 是否处于可编辑状态 --> 
  <attr name="framecolor" format="color" />     <!-- 边框颜色 --> 
  <attr name="framewidth" format="dimension" />   <!-- 边框线宽度 --> 
  <attr name="framepadding" format="dimension" />  <!-- 边框与图片的间距 --> 
  <attr name="degree" format="float" />       <!-- 旋转角度 --> 
  <attr name="scale" format="float" />       <!-- 缩放比例 --> 
  <attr name="controldrawable" format="reference"/> <!-- 控制图标 --> 
  <attr name="controllocation">           <!-- 控制图标的位置 --> 
    <enum name="left_top" value="0" /> 
    <enum name="right_top" value="1" /> 
    <enum name="right_bottom" value="2" /> 
    <enum name="left_bottom" value="3" /> 
  </attr> 
</declare-styleable> 

接下来就是自定义singletouchview的代码,代码有点长,注释还是蛮详细的

package com.example.singletouchview; 
 
import java.util.arrays; 
import java.util.collections; 
import java.util.list; 
 
import android.content.context; 
import android.content.res.typedarray; 
import android.graphics.bitmap; 
import android.graphics.bitmap.config; 
import android.graphics.canvas; 
import android.graphics.color; 
import android.graphics.matrix; 
import android.graphics.paint; 
import android.graphics.paint.style; 
import android.graphics.path; 
import android.graphics.point; 
import android.graphics.pointf; 
import android.graphics.drawable.bitmapdrawable; 
import android.graphics.drawable.drawable; 
import android.util.attributeset; 
import android.util.displaymetrics; 
import android.util.floatmath; 
import android.util.typedvalue; 
import android.view.motionevent; 
import android.view.view; 
import android.view.viewgroup; 
 
/** 
 * 单手对图片进行缩放,旋转,平移操作,详情请查看 
 * 
 * @blog http://blog.csdn.net/xiaanming/article/details/42833893 
 * 
 * @author xiaanming 
 * 
 */ 
public class singletouchview extends view { 
  /** 
   * 图片的最大缩放比例 
   */ 
  public static final float max_scale = 4.0f; 
   
  /** 
   * 图片的最小缩放比例 
   */ 
  public static final float min_scale = 0.3f; 
   
  /** 
   * 控制缩放,旋转图标所在四个点得位置 
   */ 
  public static final int left_top = 0; 
  public static final int right_top = 1; 
  public static final int right_bottom = 2; 
  public static final int left_bottom = 3; 
   
  /** 
   * 一些默认的常量 
   */ 
  public static final int default_frame_padding = 8; 
  public static final int default_frame_width = 2; 
  public static final int default_frame_color = color.white; 
  public static final float default_scale = 1.0f; 
  public static final float default_degree = 0; 
  public static final int default_control_location = right_top; 
  public static final boolean default_editable = true; 
  public static final int default_other_drawable_width = 50; 
  public static final int default_other_drawable_height = 50; 
   
   
   
  /** 
   * 用于旋转缩放的bitmap 
   */ 
  private bitmap mbitmap; 
   
  /** 
   * singletouchview的中心点坐标,相对于其父类布局而言的 
   */ 
  private pointf mcenterpoint = new pointf(); 
   
  /** 
   * view的宽度和高度,随着图片的旋转而变化(不包括控制旋转,缩放图片的宽高) 
   */ 
  private int mviewwidth, mviewheight; 
   
  /** 
   * 图片的旋转角度 
   */ 
  private float mdegree = default_degree; 
   
  /** 
   * 图片的缩放比例 
   */ 
  private float mscale = default_scale; 
   
  /** 
   * 用于缩放,旋转,平移的矩阵 
   */ 
  private matrix matrix = new matrix(); 
   
  /** 
   * singletouchview距离父类布局的左间距 
   */ 
  private int mviewpaddingleft; 
   
  /** 
   * singletouchview距离父类布局的上间距 
   */ 
  private int mviewpaddingtop; 
   
  /** 
   * 图片四个点坐标 
   */ 
  private point mltpoint; 
  private point mrtpoint; 
  private point mrbpoint; 
  private point mlbpoint; 
   
  /** 
   * 用于缩放,旋转的控制点的坐标 
   */ 
  private point mcontrolpoint = new point(); 
   
  /** 
   * 用于缩放,旋转的图标 
   */ 
  private drawable controldrawable; 
   
  /** 
   * 缩放,旋转图标的宽和高 
   */ 
  private int mdrawablewidth, mdrawableheight; 
   
  /** 
   * 画外围框的path 
   */ 
  private path mpath = new path(); 
   
  /** 
   * 画外围框的画笔 
   */ 
  private paint mpaint ; 
   
  /** 
   * 初始状态 
   */ 
  public static final int status_init = 0; 
   
  /** 
   * 拖动状态 
   */ 
  public static final int status_drag = 1; 
   
  /** 
   * 旋转或者放大状态 
   */ 
  public static final int status_rotate_zoom = 2;  
   
  /** 
   * 当前所处的状态 
   */ 
  private int mstatus = status_init; 
   
  /** 
   * 外边框与图片之间的间距, 单位是dip 
   */ 
  private int framepadding = default_frame_padding; 
   
  /** 
   * 外边框颜色 
   */ 
  private int framecolor = default_frame_color; 
   
  /** 
   * 外边框线条粗细, 单位是 dip 
   */ 
  private int framewidth = default_frame_width; 
   
  /** 
   * 是否处于可以缩放,平移,旋转状态 
   */ 
  private boolean iseditable = default_editable; 
   
  private displaymetrics metrics; 
   
   
  private pointf mpremovepointf = new pointf(); 
  private pointf mcurmovepointf = new pointf(); 
   
  /** 
   * 图片在旋转时x方向的偏移量 
   */ 
  private int offsetx; 
  /** 
   * 图片在旋转时y方向的偏移量 
   */ 
  private int offsety; 
   
  /** 
   * 控制图标所在的位置(比如左上,右上,左下,右下) 
   */ 
  private int controllocation = default_control_location; 
 
   
  public singletouchview(context context, attributeset attrs) { 
    this(context, attrs, 0); 
  } 
 
  public singletouchview(context context) { 
    this(context, null); 
  } 
 
  public singletouchview(context context, attributeset attrs, int defstyle) { 
    super(context, attrs, defstyle); 
    obtainstyledattributes(attrs); 
    init(); 
  } 
   
  /** 
   * 获取自定义属性 
   * @param attrs 
   */ 
  private void obtainstyledattributes(attributeset attrs){ 
    metrics = getcontext().getresources().getdisplaymetrics(); 
    framepadding = (int) typedvalue.applydimension(typedvalue.complex_unit_dip, default_frame_padding, metrics); 
    framewidth = (int) typedvalue.applydimension(typedvalue.complex_unit_dip, default_frame_width, metrics); 
     
    typedarray mtypedarray = getcontext().obtainstyledattributes(attrs, 
        r.styleable.singletouchview); 
     
    drawable srcdrawble = mtypedarray.getdrawable(r.styleable.singletouchview_src); 
    mbitmap = drawable2bitmap(srcdrawble); 
     
    framepadding = mtypedarray.getdimensionpixelsize(r.styleable.singletouchview_framepadding, framepadding); 
    framewidth = mtypedarray.getdimensionpixelsize(r.styleable.singletouchview_framewidth, framewidth); 
    framecolor = mtypedarray.getcolor(r.styleable.singletouchview_framecolor, default_frame_color); 
    mscale = mtypedarray.getfloat(r.styleable.singletouchview_scale, default_scale); 
    mdegree = mtypedarray.getfloat(r.styleable.singletouchview_degree, default_degree); 
    controldrawable = mtypedarray.getdrawable(r.styleable.singletouchview_controldrawable); 
    controllocation = mtypedarray.getint(r.styleable.singletouchview_controllocation, default_control_location); 
    iseditable = mtypedarray.getboolean(r.styleable.singletouchview_editable, default_editable); 
     
    mtypedarray.recycle(); 
     
  } 
   
   
  private void init(){ 
    mpaint = new paint(); 
    mpaint.setantialias(true); 
    mpaint.setcolor(framecolor); 
    mpaint.setstrokewidth(framewidth); 
    mpaint.setstyle(style.stroke); 
     
    if(controldrawable == null){ 
      controldrawable = getcontext().getresources().getdrawable(r.drawable.st_rotate_icon); 
    } 
     
    mdrawablewidth = controldrawable.getintrinsicwidth(); 
    mdrawableheight = controldrawable.getintrinsicheight(); 
     
    transformdraw();  
  } 
   
   
  @override 
  protected void onmeasure(int widthmeasurespec, int heightmeasurespec) { 
    super.onmeasure(widthmeasurespec, heightmeasurespec); 
     
    //获取singletouchview所在父布局的中心点 
    viewgroup mviewgroup = (viewgroup) getparent(); 
    if(null != mviewgroup){ 
      int parentwidth = mviewgroup.getwidth(); 
      int parentheight = mviewgroup.getheight(); 
      mcenterpoint.set(parentwidth/2, parentheight/2); 
    } 
  } 
   
   
  /** 
   * 调整view的大小,位置 
   */ 
  private void adjustlayout(){ 
    int actualwidth = mviewwidth + mdrawablewidth; 
    int actualheight = mviewheight + mdrawableheight; 
     
    int newpaddingleft = (int) (mcenterpoint.x - actualwidth /2); 
    int newpaddingtop = (int) (mcenterpoint.y - actualheight/2); 
     
    if(mviewpaddingleft != newpaddingleft || mviewpaddingtop != newpaddingtop){ 
      mviewpaddingleft = newpaddingleft; 
      mviewpaddingtop = newpaddingtop; 
       
//     layout(newpaddingleft, newpaddingtop, newpaddingleft + actualwidth, newpaddingtop + actualheight); 
    } 
     
    layout(newpaddingleft, newpaddingtop, newpaddingleft + actualwidth, newpaddingtop + actualheight); 
  } 
   
   
  /** 
   * 设置旋转图 
   * @param bitmap 
   */ 
  public void setimagebitamp(bitmap bitmap){ 
    this.mbitmap = bitmap; 
    transformdraw(); 
  } 
   
   
  /** 
   * 设置旋转图 
   * @param drawable 
   */ 
  public void setimagedrawable(drawable drawable){ 
    this.mbitmap = drawable2bitmap(drawable); 
    transformdraw(); 
  } 
   
  /** 
   * 从drawable中获取bitmap对象 
   * @param drawable 
   * @return 
   */ 
  private bitmap drawable2bitmap(drawable drawable) { 
    try { 
      if (drawable == null) { 
        return null; 
      } 
 
      if (drawable instanceof bitmapdrawable) { 
        return ((bitmapdrawable) drawable).getbitmap(); 
      } 
 
      int intrinsicwidth = drawable.getintrinsicwidth(); 
      int intrinsicheight = drawable.getintrinsicheight(); 
      bitmap bitmap = bitmap.createbitmap( 
          intrinsicwidth <= 0 ? default_other_drawable_width 
              : intrinsicwidth, 
          intrinsicheight <= 0 ? default_other_drawable_height 
              : intrinsicheight, config.argb_8888); 
 
      canvas canvas = new canvas(bitmap); 
      drawable.setbounds(0, 0, canvas.getwidth(), canvas.getheight()); 
      drawable.draw(canvas); 
      return bitmap; 
    } catch (outofmemoryerror e) { 
      return null; 
    } 
 
  } 
   
  /** 
   * 根据id设置旋转图 
   * @param resid 
   */ 
  public void setimageresource(int resid){ 
    drawable drawable = getcontext().getresources().getdrawable(resid); 
    setimagedrawable(drawable); 
  } 
   
  @override 
  protected void ondraw(canvas canvas) { 
    //每次draw之前调整view的位置和大小 
    super.ondraw(canvas); 
     
    if(mbitmap == null) return; 
    canvas.drawbitmap(mbitmap, matrix, mpaint); 
     
     
    //处于可编辑状态才画边框和控制图标 
    if(iseditable){ 
      mpath.reset(); 
      mpath.moveto(mltpoint.x, mltpoint.y); 
      mpath.lineto(mrtpoint.x, mrtpoint.y); 
      mpath.lineto(mrbpoint.x, mrbpoint.y); 
      mpath.lineto(mlbpoint.x, mlbpoint.y); 
      mpath.lineto(mltpoint.x, mltpoint.y); 
      mpath.lineto(mrtpoint.x, mrtpoint.y); 
      canvas.drawpath(mpath, mpaint); 
      //画旋转, 缩放图标 
       
      controldrawable.setbounds(mcontrolpoint.x - mdrawablewidth / 2, 
          mcontrolpoint.y - mdrawableheight / 2, mcontrolpoint.x + mdrawablewidth 
              / 2, mcontrolpoint.y + mdrawableheight / 2); 
      controldrawable.draw(canvas); 
    } 
     
    adjustlayout(); 
     
     
  } 
   
   
   
  /** 
   * 设置matrix, 强制刷新 
   */ 
  private void transformdraw(){ 
    if(mbitmap == null) return; 
    int bitmapwidth = (int)(mbitmap.getwidth() * mscale); 
    int bitmapheight = (int)(mbitmap.getheight()* mscale); 
    computerect(-framepadding, -framepadding, bitmapwidth + framepadding, bitmapheight + framepadding, mdegree); 
     
    //设置缩放比例 
    matrix.setscale(mscale, mscale); 
    //绕着图片中心进行旋转 
    matrix.postrotate(mdegree % 360, bitmapwidth/2, bitmapheight/2); 
    //设置画该图片的起始点 
    matrix.posttranslate(offsetx + mdrawablewidth/2, offsety + mdrawableheight/2); 
     
    adjustlayout(); 
  } 
   
   
  public boolean ontouchevent(motionevent event) { 
    if(!iseditable){ 
      return super.ontouchevent(event); 
    } 
    switch (event.getaction() ) { 
    case motionevent.action_down: 
      mpremovepointf.set(event.getx() + mviewpaddingleft, event.gety() + mviewpaddingtop); 
       
      mstatus = judgestatus(event.getx(), event.gety()); 
 
      break; 
    case motionevent.action_up: 
      mstatus = status_init; 
      break; 
    case motionevent.action_move: 
      mcurmovepointf.set(event.getx() + mviewpaddingleft, event.gety() + mviewpaddingtop); 
      if (mstatus == status_rotate_zoom) { 
        float scale = 1f; 
         
        int halfbitmapwidth = mbitmap.getwidth() / 2; 
        int halfbitmapheight = mbitmap.getheight() /2 ; 
         
        //图片某个点到图片中心的距离 
        float bitmaptocenterdistance = floatmath.sqrt(halfbitmapwidth * halfbitmapwidth + halfbitmapheight * halfbitmapheight); 
         
        //移动的点到图片中心的距离 
        float movetocenterdistance = distance4pointf(mcenterpoint, mcurmovepointf); 
         
        //计算缩放比例 
        scale = movetocenterdistance / bitmaptocenterdistance; 
         
         
        //缩放比例的界限判断 
        if (scale <= min_scale) { 
          scale = min_scale; 
        } else if (scale >= max_scale) { 
          scale = max_scale; 
        } 
         
         
        // 角度 
        double a = distance4pointf(mcenterpoint, mpremovepointf); 
        double b = distance4pointf(mpremovepointf, mcurmovepointf); 
        double c = distance4pointf(mcenterpoint, mcurmovepointf); 
         
        double cosb = (a * a + c * c - b * b) / (2 * a * c); 
         
        if (cosb >= 1) { 
          cosb = 1f; 
        } 
         
        double radian = math.acos(cosb); 
        float newdegree = (float) radiantodegree(radian); 
         
        //center -> promove的向量, 我们使用pointf来实现 
        pointf centertopromove = new pointf((mpremovepointf.x - mcenterpoint.x), (mpremovepointf.y - mcenterpoint.y)); 
         
        //center -> curmove 的向量  
        pointf centertocurmove = new pointf((mcurmovepointf.x - mcenterpoint.x), (mcurmovepointf.y - mcenterpoint.y)); 
         
        //向量叉乘结果, 如果结果为负数, 表示为逆时针, 结果为正数表示顺时针 
        float result = centertopromove.x * centertocurmove.y - centertopromove.y * centertocurmove.x; 
 
        if (result < 0) { 
          newdegree = -newdegree; 
        }  
         
        mdegree = mdegree + newdegree; 
        mscale = scale; 
         
        transformdraw(); 
      } 
      else if (mstatus == status_drag) { 
        // 修改中心点 
        mcenterpoint.x += mcurmovepointf.x - mpremovepointf.x; 
        mcenterpoint.y += mcurmovepointf.y - mpremovepointf.y; 
         
        system.out.println(this + "move = " + mcenterpoint); 
         
        adjustlayout(); 
      } 
       
      mpremovepointf.set(mcurmovepointf); 
      break; 
    } 
    return true; 
  } 
   
   
   
  /** 
   * 获取四个点和view的大小 
   * @param left 
   * @param top 
   * @param right 
   * @param bottom 
   * @param degree 
   */ 
  private void computerect(int left, int top, int right, int bottom, float degree){ 
    point lt = new point(left, top); 
    point rt = new point(right, top); 
    point rb = new point(right, bottom); 
    point lb = new point(left, bottom); 
    point cp = new point((left + right) / 2, (top + bottom) / 2); 
    mltpoint = obtainroationpoint(cp, lt, degree); 
    mrtpoint = obtainroationpoint(cp, rt, degree); 
    mrbpoint = obtainroationpoint(cp, rb, degree); 
    mlbpoint = obtainroationpoint(cp, lb, degree); 
     
    //计算x坐标最大的值和最小的值 
    int maxcoordinatex = getmaxvalue(mltpoint.x, mrtpoint.x, mrbpoint.x, mlbpoint.x); 
    int mincoordinatex = getminvalue(mltpoint.x, mrtpoint.x, mrbpoint.x, mlbpoint.x);; 
     
    mviewwidth = maxcoordinatex - mincoordinatex ; 
     
     
    //计算y坐标最大的值和最小的值 
    int maxcoordinatey = getmaxvalue(mltpoint.y, mrtpoint.y, mrbpoint.y, mlbpoint.y); 
    int mincoordinatey = getminvalue(mltpoint.y, mrtpoint.y, mrbpoint.y, mlbpoint.y); 
 
    mviewheight = maxcoordinatey - mincoordinatey ; 
     
     
    //view中心点的坐标 
    point viewcenterpoint = new point((maxcoordinatex + mincoordinatex) / 2, (maxcoordinatey + mincoordinatey) / 2); 
     
    offsetx = mviewwidth / 2 - viewcenterpoint.x; 
    offsety = mviewheight / 2 - viewcenterpoint.y; 
     
     
     
    int halfdrawablewidth = mdrawablewidth / 2; 
    int halfdrawableheight = mdrawableheight /2; 
     
    //将bitmap的四个点的x的坐标移动offsetx + halfdrawablewidth 
    mltpoint.x += (offsetx + halfdrawablewidth); 
    mrtpoint.x += (offsetx + halfdrawablewidth); 
    mrbpoint.x += (offsetx + halfdrawablewidth); 
    mlbpoint.x += (offsetx + halfdrawablewidth); 
 
    //将bitmap的四个点的y坐标移动offsety + halfdrawableheight 
    mltpoint.y += (offsety + halfdrawableheight); 
    mrtpoint.y += (offsety + halfdrawableheight); 
    mrbpoint.y += (offsety + halfdrawableheight); 
    mlbpoint.y += (offsety + halfdrawableheight); 
     
    mcontrolpoint = locationtopoint(controllocation); 
  } 
   
   
  /** 
   * 根据位置判断控制图标处于那个点 
   * @return 
   */ 
  private point locationtopoint(int location){ 
    switch(location){ 
    case left_top: 
      return mltpoint; 
    case right_top: 
      return mrtpoint; 
    case right_bottom: 
      return mrbpoint; 
    case left_bottom: 
      return mlbpoint; 
    } 
    return mltpoint; 
  } 
   
   
  /** 
   * 获取变长参数最大的值 
   * @param array 
   * @return 
   */ 
  public int getmaxvalue(integer...array){ 
    list<integer> list = arrays.aslist(array); 
    collections.sort(list); 
    return list.get(list.size() -1); 
  } 
   
   
  /** 
   * 获取变长参数最大的值 
   * @param array 
   * @return 
   */ 
  public int getminvalue(integer...array){ 
    list<integer> list = arrays.aslist(array); 
    collections.sort(list); 
    return list.get(0); 
  } 
   
   
   
  /** 
   * 获取旋转某个角度之后的点 
   * @param viewcenter 
   * @param source 
   * @param degree 
   * @return 
   */ 
  public static point obtainroationpoint(point center, point source, float degree) { 
    //两者之间的距离 
    point dispoint = new point(); 
    dispoint.x = source.x - center.x; 
    dispoint.y = source.y - center.y; 
     
    //没旋转之前的弧度 
    double originradian = 0; 
 
    //没旋转之前的角度 
    double origindegree = 0; 
     
    //旋转之后的角度 
    double resultdegree = 0; 
     
    //旋转之后的弧度 
    double resultradian = 0; 
     
    //经过旋转之后点的坐标 
    point resultpoint = new point(); 
     
    double distance = math.sqrt(dispoint.x * dispoint.x + dispoint.y * dispoint.y); 
    if (dispoint.x == 0 && dispoint.y == 0) { 
      return center; 
      // 第一象限 
    } else if (dispoint.x >= 0 && dispoint.y >= 0) { 
      // 计算与x正方向的夹角 
      originradian = math.asin(dispoint.y / distance); 
       
      // 第二象限 
    } else if (dispoint.x < 0 && dispoint.y >= 0) { 
      // 计算与x正方向的夹角 
      originradian = math.asin(math.abs(dispoint.x) / distance); 
      originradian = originradian + math.pi / 2; 
       
      // 第三象限 
    } else if (dispoint.x < 0 && dispoint.y < 0) { 
      // 计算与x正方向的夹角 
      originradian = math.asin(math.abs(dispoint.y) / distance); 
      originradian = originradian + math.pi; 
    } else if (dispoint.x >= 0 && dispoint.y < 0) { 
      // 计算与x正方向的夹角 
      originradian = math.asin(dispoint.x / distance); 
      originradian = originradian + math.pi * 3 / 2; 
    } 
     
    // 弧度换算成角度 
    origindegree = radiantodegree(originradian); 
    resultdegree = origindegree + degree; 
     
    // 角度转弧度 
    resultradian = degreetoradian(resultdegree); 
     
    resultpoint.x = (int) math.round(distance * math.cos(resultradian)); 
    resultpoint.y = (int) math.round(distance * math.sin(resultradian)); 
    resultpoint.x += center.x; 
    resultpoint.y += center.y; 
 
    return resultpoint; 
  } 
 
  /** 
   * 弧度换算成角度 
   * 
   * @return 
   */ 
  public static double radiantodegree(double radian) { 
    return radian * 180 / math.pi; 
  } 
 
   
  /** 
   * 角度换算成弧度 
   * @param degree 
   * @return 
   */ 
  public static double degreetoradian(double degree) { 
    return degree * math.pi / 180; 
  } 
   
  /** 
   * 根据点击的位置判断是否点中控制旋转,缩放的图片, 初略的计算 
   * @param x 
   * @param y 
   * @return 
   */ 
  private int judgestatus(float x, float y){ 
    pointf touchpoint = new pointf(x, y); 
    pointf controlpointf = new pointf(mcontrolpoint); 
     
    //点击的点到控制旋转,缩放点的距离 
    float distancetocontrol = distance4pointf(touchpoint, controlpointf); 
     
    //如果两者之间的距离小于 控制图标的宽度,高度的最小值,则认为点中了控制图标 
    if(distancetocontrol < math.min(mdrawablewidth/2, mdrawableheight/2)){ 
      return status_rotate_zoom; 
    } 
     
    return status_drag; 
     
  } 
   
   
  public float getimagedegree() { 
    return mdegree; 
  } 
 
  /** 
   * 设置图片旋转角度 
   * @param degree 
   */ 
  public void setimagedegree(float degree) { 
    if(this.mdegree != degree){ 
      this.mdegree = degree; 
      transformdraw(); 
    } 
  } 
 
  public float getimagescale() { 
    return mscale; 
  } 
 
  /** 
   * 设置图片缩放比例 
   * @param scale 
   */ 
  public void setimagescale(float scale) { 
    if(this.mscale != scale){ 
      this.mscale = scale; 
      transformdraw(); 
    }; 
  } 
   
 
  public drawable getcontroldrawable() { 
    return controldrawable; 
  } 
 
  /** 
   * 设置控制图标 
   * @param drawable 
   */ 
  public void setcontroldrawable(drawable drawable) { 
    this.controldrawable = drawable; 
    mdrawablewidth = drawable.getintrinsicwidth(); 
    mdrawableheight = drawable.getintrinsicheight(); 
    transformdraw(); 
  } 
 
  public int getframepadding() { 
    return framepadding; 
  } 
 
  public void setframepadding(int framepadding) { 
    if(this.framepadding == framepadding) 
      return; 
    this.framepadding = (int) typedvalue.applydimension(typedvalue.complex_unit_dip, framepadding, metrics); 
    transformdraw(); 
  } 
 
  public int getframecolor() { 
    return framecolor; 
  } 
 
  public void setframecolor(int framecolor) { 
    if(this.framecolor == framecolor) 
      return; 
    this.framecolor = framecolor; 
    mpaint.setcolor(framecolor); 
    invalidate(); 
  } 
 
  public int getframewidth() { 
    return framewidth; 
  } 
 
  public void setframewidth(int framewidth) { 
    if(this.framewidth == framewidth)  
      return; 
    this.framewidth = (int) typedvalue.applydimension(typedvalue.complex_unit_dip, framewidth, metrics); 
    mpaint.setstrokewidth(framewidth); 
    invalidate(); 
  } 
   
  /** 
   * 设置控制图标的位置, 设置的值只能选择left_top ,right_top, right_bottom,left_bottom 
   * @param controllocation 
   */ 
  public void setcontrollocation(int location) { 
    if(this.controllocation == location) 
      return; 
    this.controllocation = location; 
    transformdraw(); 
  } 
 
  public int getcontrollocation() { 
    return controllocation; 
  } 
   
   
 
  public pointf getcenterpoint() { 
    return mcenterpoint; 
  } 
 
  /** 
   * 设置图片中心点位置,相对于父布局而言 
   * @param mcenterpoint 
   */ 
  public void setcenterpoint(pointf mcenterpoint) { 
    this.mcenterpoint = mcenterpoint; 
    adjustlayout(); 
  } 
   
 
  public boolean iseditable() { 
    return iseditable; 
  } 
 
  /** 
   * 设置是否处于可缩放,平移,旋转状态 
   * @param iseditable 
   */ 
  public void seteditable(boolean iseditable) { 
    this.iseditable = iseditable; 
    invalidate(); 
  } 
 
  /** 
   * 两个点之间的距离 
   * @param x1 
   * @param y1 
   * @param x2 
   * @param y2 
   * @return 
   */ 
  private float distance4pointf(pointf pf1, pointf pf2) { 
    float disx = pf2.x - pf1.x; 
    float disy = pf2.y - pf1.y; 
    return floatmath.sqrt(disx * disx + disy * disy); 
  } 
   
 
} 

为了让singletouchview居中,我们需要获取父布局的长和宽,我们在onmeasure()中来获取,当然如果我们不需要居中显示我们也可以调用setcenterpoint方法来设置其位置.

ontouchevent()方法中,mpremovepointf和mcurmovepointf点的坐标不是相对view来的,首先如果采用相对于view本身(getx(), gety())肯定是不行的,假如你往x轴方向移动一段距离,这个singletouchview也会移动一段距离,mpremovepointf和mcurmovepointf点和singletouchview的中心点都是会变化的,所以在移动的时候会不停的闪烁,相对于屏幕左上角(getrawx(), getrawy())是可以的,但是由于mcenterpointf并不是相对于屏幕的坐标,而是相对于父类布局的,所以将需要将mpremovepointf和mcurmovepointf的坐标换算成相对于父类布局。

这里面最重要的方法就是transformdraw()方法,它主要做的是调用computerect()方法求出图片的四个角的坐标点mltpoint,mrtpoint,mrbpoint,mlbpoint(这几点的坐标是相对于singletouchview本身)和singletouchview的宽度和高度,以及控制图标所在图标四个点中的哪个点。如下图

Android单点触控实现图片平移、缩放、旋转功能

上面的图忽略了控制旋转,缩放图标,黑色的框是开始的view的大小,而经过旋转之后,view的大小变成最外层的虚线框了,所以我们需要调用adjustlayout()方法来重新设置view的位置和大小,接下来就是设置matrix了

matrix.setscale(mscale, mscale); 
matrix.postrotate(mdegree % 360, bitmapwidth/2, bitmapheight/2); 
matrix.posttranslate(offsetx + mdrawablewidth/2, offsety + mdrawableheight/2); 

先设置缩放比例, 然后设置围绕图片的中心点旋转mdegree,posttranslate( float dx, float dy)方法是画该图片的起始点进行平移dx, dy个单位,而不是移动到dx,dy这个点。
接下来就来使用,定义一个xml布局文件

<merge xmlns:android="http://schemas.android.com/apk/res/android" 
  xmlns:tools="http://schemas.android.com/tools"> 
 
    <com.example.singletouchview.singletouchview 
      xmlns:app="http://schemas.android.com/apk/res-auto" 
      android:id="@+id/singletouchview" 
      android:layout_width="match_parent" 
      android:layout_height="match_parent" 
      app:scale="1.2" 
      app:src="@drawable/scale" 
      app:framecolor="#0022ff" 
      app:controllocation="right_top"/> 
 
</merge> 

在里面写了一些自定义的属性,写自定义属性之前需要声明xmlns:app="http://schemas.android.com/apk/res-auto",activity只需要设置这个布局文件作为contentview就行了,接下来运行程序看下效果。

Android单点触控实现图片平移、缩放、旋转功能

怎么样?效果还是不错的吧,如果我们想去掉蓝色的边框和用于缩放旋转的小图标,直接调用seteditable(false)就可以了,设置了seteditable(false)该view的点击事件,长按事件是正常的。

以上就是本文的全部内容,希望对大家学习android软件编程有所帮助。