Android中利用matrix 控制图片的旋转、缩放、移动

本文主要讲解利用android中Matrix控制图形的旋转缩放移动,具体参见一下代码:


代码如下:

/**
 * 使用矩阵控制图片移动、缩放、旋转
 */ 
public class CommonImgEffectView extends View {

private Context context ; 
    private Bitmap mainBmp , controlBmp ; 
    private int mainBmpWidth , mainBmpHeight , controlBmpWidth , controlBmpHeight ; 
    private Matrix matrix ;  
    private float [] srcPs , dstPs ; 
    private RectF srcRect , dstRect ; 
    private Paint paint ,paintRect , paintFrame; 
    private float deltaX = 0, deltaY = 0; //位移值 
    private float scaleValue = 1; //缩放值 
    private Point lastPoint ; 
    private Point prePivot , lastPivot; 
    private float preDegree , lastDegree ; 
    private short currentSelectedPointindex;        //当前操作点击点 
    private Point symmetricPoint  = new Point();    //当前操作点对称点

/**
     * 图片操作类型
     */ 
    public static final int OPER_DEFAULT = -1;      //默认 
    public static final int OPER_TRANSLATE = 0;     //移动 
    public static final int OPER_SCALE = 1;         //缩放 
    public static final int OPER_ROTATE = 2;        //旋转 
    public static final int OPER_SELECTED = 3;      //选择 
    public int lastOper = OPER_DEFAULT;

/* 图片控制点
     * 0---1---2
     * |       |
     * 7   8   3
     * |       |
     * 6---5---4 
     */ 
    public static final int CTR_NONE = -1; 
    public static final int CTR_LEFT_TOP = 0; 
    public static final int CTR_MID_TOP = 1; 
    public static final int CTR_RIGHT_TOP = 2; 
    public static final int CTR_RIGHT_MID = 3; 
    public static final int CTR_RIGHT_BOTTOM = 4; 
    public static final int CTR_MID_BOTTOM = 5; 
    public static final int CTR_LEFT_BOTTOM = 6; 
    public static final int CTR_LEFT_MID = 7; 
    public static final int CTR_MID_MID = 8; 
    public int current_ctr = CTR_NONE;

public CommonImgEffectView(Context context){ 
        super(context); 
        this.context = context ; 
    }

public CommonImgEffectView(Context context, AttributeSet attrs) { 
        super(context, attrs); 
        this.context = context ; 
        initData(); 
    }

/**
     * 初始化数据
     * @author 张进
     */ 
    private void initData(){ 
        mainBmp = BitmapFactory.decodeResource(this.context.getResources(), R.drawable.flower); 
        controlBmp = BitmapFactory.decodeResource(this.context.getResources(), R.drawable.control); 
        mainBmpWidth = mainBmp.getWidth(); 
        mainBmpHeight = mainBmp.getHeight(); 
        controlBmpWidth = controlBmp.getWidth(); 
        controlBmpHeight = controlBmp.getHeight();

srcPs = new float[]{ 
                                0,0,  
                                mainBmpWidth/2,0,  
                                mainBmpWidth,0,  
                                mainBmpWidth,mainBmpHeight/2, 
                                mainBmpWidth,mainBmpHeight,  
                                mainBmpWidth/2,mainBmpHeight,  
                                0,mainBmpHeight,  
                                0,mainBmpHeight/2,  
                                mainBmpWidth/2,mainBmpHeight/2 
                            }; 
        dstPs = srcPs.clone(); 
        srcRect = new RectF(0, 0, mainBmpWidth, mainBmpHeight); 
        dstRect = new RectF();

matrix = new Matrix();

prePivot = new Point(mainBmpWidth/2, mainBmpHeight/2); 
        lastPivot = new Point(mainBmpWidth/2, mainBmpHeight/2);

lastPoint = new Point(0,0);

paint = new Paint();

paintRect = new Paint(); 
        paintRect.setColor(Color.RED); 
        paintRect.setAlpha(100); 
        paintRect.setAntiAlias(true);

paintFrame = new Paint(); 
        paintFrame.setColor(Color.GREEN); 
        paintFrame.setAntiAlias(true);

setMatrix(OPER_DEFAULT); 
    }

/**
     * 矩阵变换,达到图形平移的目的
     * @author 张进
     */ 
    private void setMatrix(int operationType){ 
        switch (operationType) { 
        case OPER_TRANSLATE: 
            matrix.postTranslate(deltaX , deltaY); 
            break; 
        case OPER_SCALE: 
            matrix.postScale(scaleValue, scaleValue, symmetricPoint.x, symmetricPoint.y); 
            break; 
        case OPER_ROTATE: 
            matrix.postRotate(preDegree - lastDegree, dstPs[CTR_MID_MID * 2], dstPs[CTR_MID_MID * 2 + 1]); 
            break; 
        }

matrix.mapPoints(dstPs, srcPs); 
        matrix.mapRect(dstRect, srcRect); 
    }

private boolean isOnPic(int x , int y){ 
        if(dstRect.contains(x, y)){ 
            return true; 
        }else  
            return false; 
    }

private int getOperationType(MotionEvent event){

int evX = (int)event.getX(); 
        int evY = (int)event.getY(); 
        int curOper = lastOper; 
        switch(event.getAction()) { 
            case MotionEvent.ACTION_DOWN: 
                current_ctr = isOnCP(evX, evY); 
                Log.i("img", "current_ctr is "+current_ctr); 
                if(current_ctr != CTR_NONE || isOnPic(evX, evY)){ 
                    curOper = OPER_SELECTED; 
                } 
                break; 
            case MotionEvent.ACTION_MOVE: 
                    if(current_ctr > CTR_NONE && current_ctr < CTR_MID_MID ){ 
                        curOper = OPER_SCALE; 
                    }else if(current_ctr == CTR_MID_MID ){ 
                        curOper = OPER_ROTATE; 
                    }else if(lastOper == OPER_SELECTED){ 
                        curOper = OPER_TRANSLATE; 
                    } 
                break; 
            case MotionEvent.ACTION_UP: 
                curOper = OPER_SELECTED; 
                break; 
            default: 
                break; 
        } 
        Log.d("img", "curOper is "+curOper); 
        return curOper;

}

/**
     * 判断点所在的控制点
     * @param evX
     * @param evY
     * @return
     */  
    private int isOnCP(int evx, int evy) { 
        Rect rect = new Rect(evx-controlBmpWidth/2,evy-controlBmpHeight/2,evx+controlBmpWidth/2,evy+controlBmpHeight/2); 
        int res = 0 ; 
        for (int i = 0; i < dstPs.length; i+=2) { 
            if(rect.contains((int)dstPs[i], (int)dstPs[i+1])){ 
                return res ; 
            } 
            ++res ;  
        } 
        return CTR_NONE; 
    }

@Override 
    public boolean dispatchTouchEvent(MotionEvent event) { 
        int evX = (int)event.getX(); 
        int evY = (int)event.getY();

int operType = OPER_DEFAULT; 
        operType = getOperationType(event);

switch (operType) { 
        case OPER_TRANSLATE: 
            translate(evX, evY); 
            break; 
        case OPER_SCALE: 
            scale(event); 
            break; 
        case OPER_ROTATE: 
            rotate(event); 
            break; 
        }

lastPoint.x = evX; 
        lastPoint.y = evY;

lastOper = operType; 
        invalidate();//重绘 
        return true; 
    }

/**
     * 移动
     * @param evx
     * @param evy
     * @author zhang_jin1
     */ 
    private void translate(int evx , int evy){

prePivot.x += evx - lastPoint.x; 
        prePivot.y += evy -lastPoint.y;

deltaX = prePivot.x - lastPivot.x; 
        deltaY = prePivot.y - lastPivot.y;

lastPivot.x = prePivot.x; 
        lastPivot.y = prePivot.y;

setMatrix(OPER_TRANSLATE); //设置矩阵

}

/**
     * 缩放
     * 0---1---2
     * |       |
     * 7   8   3
     * |       |
     * 6---5---4
     * @param evX
     * @param evY
     */ 
    private void scale(MotionEvent event) {

int pointIndex = current_ctr*2 ;

float px = dstPs[pointIndex]; 
        float py = dstPs[pointIndex+1];

float evx = event.getX(); 
        float evy = event.getY();

float oppositeX = 0 ; 
        float oppositeY = 0 ; 
        if(current_ctr<4 && current_ctr >= 0){ 
             oppositeX = dstPs[pointIndex+8]; 
             oppositeY = dstPs[pointIndex+9]; 
        }else if(current_ctr >= 4){ 
             oppositeX = dstPs[pointIndex-8]; 
             oppositeY = dstPs[pointIndex-7]; 
        } 
        float temp1 = getDistanceOfTwoPoints(px,py,oppositeX,oppositeY); 
        float temp2 = getDistanceOfTwoPoints(evx,evy,oppositeX,oppositeY);

this.scaleValue = temp2 / temp1 ; 
        symmetricPoint.x = (int) oppositeX; 
        symmetricPoint.y = (int)oppositeY;

Log.i("img", "scaleValue is "+scaleValue); 
        setMatrix(OPER_SCALE); 
    }

/**
     * 旋转图片
     * 0---1---2
     * |       |
     * 7   8   3
     * |       |
     * 6---5---4 
     * @param evX
     * @param evY
     */ 
    private void rotate(MotionEvent event) {

if(event.getPointerCount() == 2){ 
            preDegree = computeDegree(new Point((int)event.getX(0), (int)event.getY(0)), new Point((int)event.getX(1), (int)event.getY(1))); 
        }else{ 
            preDegree = computeDegree(new Point((int)event.getX(), (int)event.getY()), new Point((int)dstPs[16], (int)dstPs[17])); 
        } 
        setMatrix(OPER_ROTATE); 
        lastDegree = preDegree; 
    }

/**
     * 计算两点与垂直方向夹角
     * @param p1
     * @param p2
     * @return
     */ 
    public float computeDegree(Point p1, Point p2){ 
        float tran_x = p1.x - p2.x; 
        float tran_y = p1.y - p2.y; 
        float degree = 0.0f; 
        float angle = (float)(Math.asin(tran_x/Math.sqrt(tran_x*tran_x + tran_y* tran_y))*180/Math.PI); 
        if(!Float.isNaN(angle)){ 
            if(tran_x >= 0 && tran_y <= 0){//第一象限 
                degree = angle; 
            }else if(tran_x <= 0 && tran_y <= 0){//第二象限 
                degree = angle; 
            }else if(tran_x <= 0 && tran_y >= 0){//第三象限 
                degree = -180 - angle; 
            }else if(tran_x >= 0 && tran_y >= 0){//第四象限 
                degree = 180 - angle; 
            } 
        } 
        return degree; 
    }

/**
     * 计算两个点之间的距离
     * @param p1
     * @param p2
     * @return
     */ 
    private float getDistanceOfTwoPoints(Point p1, Point p2){ 
        return (float)(Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y))); 
    }

private float getDistanceOfTwoPoints(float x1,float y1,float x2,float y2){ 
        return (float)(Math.sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2))); 
    }

@Override 
    public void onDraw(Canvas canvas){ 
        drawBackground(canvas);//绘制背景,以便测试矩形的映射 
        canvas.drawBitmap(mainBmp, matrix, paint);//绘制主图片 
        drawFrame(canvas);//绘制边框,以便测试点的映射 
        drawControlPoints(canvas);//绘制控制点图片 
    }

private void drawBackground(Canvas canvas){ 
        canvas.drawRect(dstRect, paintRect); 
    }

private void drawFrame(Canvas canvas){ 
        canvas.drawLine(dstPs[0], dstPs[1], dstPs[4], dstPs[5], paintFrame); 
        canvas.drawLine(dstPs[4], dstPs[5], dstPs[8], dstPs[9], paintFrame); 
        canvas.drawLine(dstPs[8], dstPs[9], dstPs[12], dstPs[13], paintFrame); 
        canvas.drawLine(dstPs[0], dstPs[1], dstPs[12], dstPs[13], paintFrame); 
        canvas.drawPoint(dstPs[16], dstPs[17], paintFrame); 
    }

private void drawControlPoints(Canvas canvas){

for (int i = 0; i < dstPs.length; i+=2) { 
            canvas.drawBitmap(controlBmp, dstPs[i]-controlBmpWidth/2, dstPs[i+1]-controlBmpHeight/2, paint); 
        }

}

}

Demo效果:

(0)

相关推荐

  • Android多点触控实现对图片放大缩小平移,惯性滑动等功能

    文章将在原有基础之上做了一些扩展功能: 1.图片的惯性滑动 2.图片缩放小于正常比例时,松手会自动回弹成正常比例 3.图片缩放大于最大比例时,松手会自动回弹成最大比例 实现图片的缩放,平移,双击缩放等基本功能的代码如下,每一行代码我都做了详细的注释 public class ZoomImageView extends ImageView implements ScaleGestureDetector.OnScaleGestureListener, View.OnTouchListener , V

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

    相信大家使用多点对图片进行缩放,平移的操作很熟悉了,大部分大图的浏览都具有此功能,有些app还可以对图片进行旋转操作,QQ的大图浏览就可以对图片进行旋转操作,大家都知道对图片进行缩放,平移,旋转等操作可以使用Matrix来实现,Matrix就是一个3X3的矩阵,对图片的处理可分为四个基础变换操作,Translate(平移变换).Rotate(旋转变换).Scale (缩放变换).Skew(错切变换),如果大家对Matrix不太了解的话可以看看这篇文章(点击查看),作者对每一种Matrix的变换写

  • 基于Android 实现图片平移、缩放、旋转同时进行

    前言 之前因为项目需求,其中使用到了图片的单击显示取消,图片平移缩放功能,昨天突然想再加上图片的旋转功能,在网上看了很多相关的例子,可是没看到能同时实现我想要的功能的. 需求: (1)图片平移.缩放.旋转等一系列操作后,图片需要自动居中显示. (2)图片旋转后选自动水平显示或者垂直显示 (3)图片在放大缩小的同时都能旋转 Demo实现部分效果截图 Demo主要代码 Java MainActivity.java package com.practice.noyet.rotatezoomimagev

  • Android开发实现图片平移、缩放、倒影及旋转功能的方法

    本文实例讲述了Android开发实现图片平移.缩放.倒影及旋转功能的方法.分享给大家供大家参考,具体如下: 解析: 1)根据原来的图片创建新的图片 Bitmap modBm = Bitmap.createBitmap(bm.getWidth()+20, bm.getHeight()+20, bm.getConfig()); 2)设置到画布 Canvas canvas = new Canvas(modBm); 3)使用矩阵进行平移- Matrix matrix = new Matrix(); ma

  • Android实现手势滑动多点触摸缩放平移图片效果

    现在app中,图片预览功能肯定是少不了的,用户基本已经形成条件反射,看到小图,点击看大图,看到大图两个手指开始进行放大,放大后,开始移动到指定部位. 一.概述 想要做到图片支持多点触控,自由的进行缩放.平移,需要了解几个知识点:Matrix , GestureDetector , ScaleGestureDetector 以及事件分发机制,ps:不会咋办,不会你懂的. 1.Matrix 矩阵,看深入了都是3维矩阵的乘啊什么的,怪麻烦的~~ 其实这么了解下就行了: Matrix 数据结构:3维矩阵

  • Android实现手势滑动多点触摸缩放平移图片效果(二)

    上一篇已经带大家实现了自由的放大缩小图片,简单介绍了下Matrix:具体请参考:Android实现手势滑动多点触摸缩放平移图片效果,本篇继续完善我们的ImageView. 首先加入放大后的移动. 1.自由的进行移动 我们在onTouchEvent里面,加上移动的代码,当然了,必须长或宽大于屏幕才可以移动~~~ @Override public boolean onTouch(View v, MotionEvent event) { mScaleGestureDetector.onTouchEve

  • Android 图片缩放与旋转的实现详解

    本文使用Matrix实现Android实现图片缩放与旋转.示例代码如下: 复制代码 代码如下: package com.android.matrix;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Matrix;import android.graphics.drawable.BitmapDrawable

  • Android实现对图片放大、平移和旋转的功能

    先来看看要实现的效果图 在讲解中,需要大家提前了解一些关于图片绘制的原理的相关知识. 关于实现的流程 1.自定义View 2.获得操作图片的Bitmap 3.复写View的onTouchEvent()方法中的ACTION_DOWN,ACTION_POINTER_DOWN,ACTION_MOVE,ACTION_POINTER_UP以及ACTION_UP事件. 4.定义相应图片变化的Matrix矩阵,通过手势操作的变化来设置相应的Matrix. 5.完成最终的Matrix设置时,通过invalida

  • android 图片操作(缩放移动) 实例代码

    view_show.xml 复制代码 代码如下: <?xml version="1.0" encoding="utf-8"?><LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:orientation="vertical"  android:layout_width="match_par

  • Android实现动态向Gallery中添加图片及倒影与3D效果示例

    本文实例讲述了Android实现动态向Gallery中添加图片及倒影与3D效果的方法.分享给大家供大家参考,具体如下: 在Android中gallery可以提供一个很好的显示图片的方式,实现上面的效果以及动态添加数据库或者网络上下载下来的图片资源.我们首先实现一个自定义的Gallery类. MyGallery.java: package nate.android.Service; import android.content.Context; import android.graphics.Ca

  • Android编程实现图片的浏览、缩放、拖动和自动居中效果

    本文实例讲述了Android编程实现图片的浏览.缩放.拖动和自动居中效果的方法.分享给大家供大家参考,具体如下: Touch.java /** * 图片浏览.缩放.拖动.自动居中 */ public class Touch extends Activity implements OnTouchListener { Matrix matrix = new Matrix(); Matrix savedMatrix = new Matrix(); DisplayMetrics dm; ImageVie

随机推荐