AndroidClipSquare安卓实现方形头像裁剪

安卓实现方形头像裁剪

实现思路。界面可见区域为2层View

最顶层的View是显示层,主要绘制半透明边框区域和白色裁剪区域,代码比較easy。

第二层继承ImageView,使用ImageView的Matrix实现显示部分图片,及挪动,放大缩小等操作。

比較复杂的地方在于多指操作对ImageView的影响,详见代码:

ClipSquareImageView.java

package com.h3c.androidclipsquare;

import android.annotation.TargetApi;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.util.AttributeSet;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

/**
 * Created by H3c on 12/13/14.
 */
public class ClipSquareImageView extends ImageView implements View.OnTouchListener, ViewTreeObserver.OnGlobalLayoutListener {
    private static final int BORDERDISTANCE = ClipSquareView.BORDERDISTANCE;

    public static final float DEFAULT_MAX_SCALE = 4.0f;
    public static final float DEFAULT_MID_SCALE = 2.0f;
    public static final float DEFAULT_MIN_SCALE = 1.0f;

    private float minScale = DEFAULT_MIN_SCALE;
    private float midScale = DEFAULT_MID_SCALE;
    private float maxScale = DEFAULT_MAX_SCALE;

    private MultiGestureDetector multiGestureDetector;
    private boolean isIniting;// 正在初始化

    private Matrix defaultMatrix = new Matrix();// 初始化的图片矩阵,控制图片撑满屏幕及显示区域
    private Matrix dragMatrix = new Matrix();// 拖拽放大过程中动态的矩阵
    private Matrix finalMatrix = new Matrix();// 终于显示的矩阵
    private final RectF displayRect = new RectF();// 图片的真实大小
    private final float[] matrixValues = new float[9];

    private int borderlength;

    public ClipSquareImageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        super.setScaleType(ScaleType.MATRIX);
        setOnTouchListener(this);
        multiGestureDetector = new MultiGestureDetector(context);
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        getViewTreeObserver().addOnGlobalLayoutListener(this);
    }

    @SuppressWarnings("deprecation")
    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        getViewTreeObserver().removeGlobalOnLayoutListener(this);
    }

    @Override
    public void onGlobalLayout() {
        if(isIniting) {
            return;
        }
        // 调整视图位置
        initBmpPosition();
    }

    /**
     * 初始化图片位置
     */
    private void initBmpPosition() {
        isIniting = true;
        super.setScaleType(ScaleType.MATRIX);
        Drawable drawable = getDrawable();

        if(drawable == null) {
            return;
        }

        final float viewWidth = getWidth();
        final float viewHeight = getHeight();
        final int drawableWidth = drawable.getIntrinsicWidth();
        final int drawableHeight = drawable.getIntrinsicHeight();
        if(viewWidth < viewHeight) {
            borderlength = (int) (viewWidth - 2 * BORDERDISTANCE);
        } else {
            borderlength = (int) (viewHeight - 2 * BORDERDISTANCE);
        }

        float screenScale = 1f;
        // 小于屏幕的图片会被撑满屏幕
        if(drawableWidth <= drawableHeight) {// 竖图片
            screenScale = (float) borderlength / drawableWidth;
        } else {// 横图片
            screenScale = (float) borderlength / drawableHeight;
        }

        defaultMatrix.setScale(screenScale, screenScale);

        if(drawableWidth <= drawableHeight) {// 竖图片
            float heightOffset = (viewHeight - drawableHeight * screenScale) / 2.0f;
            if(viewWidth <= viewHeight) {// 竖照片竖屏幕
                defaultMatrix.postTranslate(BORDERDISTANCE, heightOffset);
            } else {// 竖照片横屏幕
                defaultMatrix.postTranslate((viewWidth - borderlength) / 2.0f, heightOffset);
            }
        } else {
            float widthOffset = (viewWidth - drawableWidth * screenScale) / 2.0f;
            if(viewWidth <= viewHeight) {// 横照片,竖屏幕
                defaultMatrix.postTranslate(widthOffset, (viewHeight - borderlength) / 2.0f);
            } else {// 横照片,横屏幕
                defaultMatrix.postTranslate(widthOffset, BORDERDISTANCE);
            }
        }

        resetMatrix();
    }

    /**
     * Resets the Matrix back to FIT_CENTER, and then displays it.s
     */
    private void resetMatrix() {
        if(dragMatrix == null) {
            return;
        }

        dragMatrix.reset();
        setImageMatrix(getDisplayMatrix());
    }

    private Matrix getDisplayMatrix() {
        finalMatrix.set(defaultMatrix);
        finalMatrix.postConcat(dragMatrix);
        return finalMatrix;
    }

    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        return multiGestureDetector.onTouchEvent(motionEvent);
    }

    private class MultiGestureDetector extends GestureDetector.SimpleOnGestureListener implements
            ScaleGestureDetector.OnScaleGestureListener {

        private final ScaleGestureDetector scaleGestureDetector;
        private final GestureDetector gestureDetector;
        private final float scaledTouchSlop;

        private VelocityTracker velocityTracker;
        private boolean isDragging;

        private float lastTouchX;
        private float lastTouchY;
        private float lastPointerCount;// 上一次是几个手指事件

        public MultiGestureDetector(Context context) {
            scaleGestureDetector = new ScaleGestureDetector(context, this);
            gestureDetector = new GestureDetector(context, this);
            gestureDetector.setOnDoubleTapListener(this);

            final ViewConfiguration configuration = ViewConfiguration.get(context);
            scaledTouchSlop = configuration.getScaledTouchSlop();
        }

        @Override
        public boolean onScale(ScaleGestureDetector scaleGestureDetector) {
            float scale = getScale();
            float scaleFactor = scaleGestureDetector.getScaleFactor();
            if(getDrawable() != null && ((scale < maxScale && scaleFactor > 1.0f) || (scale > minScale && scaleFactor < 1.0f))){
                if(scaleFactor * scale < minScale){
                    scaleFactor = minScale / scale;
                }
                if(scaleFactor * scale > maxScale){
                    scaleFactor = maxScale / scale;
                }
                dragMatrix.postScale(scaleFactor, scaleFactor, getWidth() / 2, getHeight() / 2);
                checkAndDisplayMatrix();
            }
            return true;
        }

        @Override
        public boolean onScaleBegin(ScaleGestureDetector scaleGestureDetector) {
            return true;
        }

        @Override
        public void onScaleEnd(ScaleGestureDetector scaleGestureDetector) {}

        public boolean onTouchEvent(MotionEvent event) {
            if (gestureDetector.onTouchEvent(event)) {
                return true;
            }

            scaleGestureDetector.onTouchEvent(event);

            /*
             * Get the center x, y of all the pointers
             */
            float x = 0, y = 0;
            final int pointerCount = event.getPointerCount();
            for (int i = 0; i < pointerCount; i++) {
                x += event.getX(i);
                y += event.getY(i);
            }
            x = x / pointerCount;
            y = y / pointerCount;

            /*
             * If the pointer count has changed cancel the drag
             */
            if (pointerCount != lastPointerCount) {
                isDragging = false;
                if (velocityTracker != null) {
                    velocityTracker.clear();
                }
                lastTouchX = x;
                lastTouchY = y;
                lastPointerCount = pointerCount;
            }

            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    if (velocityTracker == null) {
                        velocityTracker = VelocityTracker.obtain();
                    } else {
                        velocityTracker.clear();
                    }
                    velocityTracker.addMovement(event);

                    lastTouchX = x;
                    lastTouchY = y;
                    isDragging = false;
                    break;
                case MotionEvent.ACTION_UP:
                case MotionEvent.ACTION_CANCEL:
                    lastPointerCount = 0;
                    if (velocityTracker != null) {
                        velocityTracker.recycle();
                        velocityTracker = null;
                    }
                    break;
                case MotionEvent.ACTION_MOVE: {
                    final float dx = x - lastTouchX, dy = y - lastTouchY;

                    if (isDragging == false) {
                        // Use Pythagoras to see if drag length is larger than
                        // touch slop
                        isDragging = Math.sqrt((dx * dx) + (dy * dy)) >= scaledTouchSlop;
                    }

                    if (isDragging) {
                        if (getDrawable() != null) {
                            dragMatrix.postTranslate(dx, dy);
                            checkAndDisplayMatrix();
                        }

                        lastTouchX = x;
                        lastTouchY = y;

                        if (velocityTracker != null) {
                            velocityTracker.addMovement(event);
                        }
                    }
                    break;
                }
            }

            return true;
        }

        @Override
        public boolean onDoubleTap(MotionEvent event) {
            try {
                float scale = getScale();
                float x = getWidth() / 2;
                float y = getHeight() / 2;

                if (scale < midScale) {
                    post(new AnimatedZoomRunnable(scale, midScale, x, y));
                } else if ((scale >= midScale) && (scale < maxScale)) {
                    post(new AnimatedZoomRunnable(scale, maxScale, x, y));
                } else {// 双击缩小小于最小值
                    post(new AnimatedZoomRunnable(scale, minScale, x, y));
                }
            } catch (Exception e) {
                // Can sometimes happen when getX() and getY() is called
            }

            return true;
        }
    }

    private class AnimatedZoomRunnable implements Runnable {
        // These are 'postScale' values, means they're compounded each iteration
        static final float ANIMATION_SCALE_PER_ITERATION_IN = 1.07f;
        static final float ANIMATION_SCALE_PER_ITERATION_OUT = 0.93f;

        private final float focalX, focalY;
        private final float targetZoom;
        private final float deltaScale;

        public AnimatedZoomRunnable(final float currentZoom, final float targetZoom,
                                    final float focalX, final float focalY) {
            this.targetZoom = targetZoom;
            this.focalX = focalX;
            this.focalY = focalY;

            if (currentZoom < targetZoom) {
                deltaScale = ANIMATION_SCALE_PER_ITERATION_IN;
            } else {
                deltaScale = ANIMATION_SCALE_PER_ITERATION_OUT;
            }
        }

        @Override
        public void run() {
            dragMatrix.postScale(deltaScale, deltaScale, focalX, focalY);
            checkAndDisplayMatrix();

            final float currentScale = getScale();

            if (((deltaScale > 1f) && (currentScale < targetZoom))
                    || ((deltaScale < 1f) && (targetZoom < currentScale))) {
                // We haven't hit our target scale yet, so post ourselves
                // again
                postOnAnimation(ClipSquareImageView.this, this);

            } else {
                // We've scaled past our target zoom, so calculate the
                // necessary scale so we're back at target zoom
                final float delta = targetZoom / currentScale;
                dragMatrix.postScale(delta, delta, focalX, focalY);
                checkAndDisplayMatrix();
            }
        }
    }

    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
    private void postOnAnimation(View view, Runnable runnable) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.postOnAnimation(runnable);
        } else {
            view.postDelayed(runnable, 16);
        }
    }

    /**
     * Returns the current scale value
     *
     * @return float - current scale value
     */
    public final float getScale() {
        dragMatrix.getValues(matrixValues);
        return matrixValues[Matrix.MSCALE_X];
    }

    /**
     * Helper method that simply checks the Matrix, and then displays the result
     */
    private void checkAndDisplayMatrix() {
        checkMatrixBounds();
        setImageMatrix(getDisplayMatrix());
    }

    private void checkMatrixBounds() {
        final RectF rect = getDisplayRect(getDisplayMatrix());
        if (null == rect) {
            return;
        }

        float deltaX = 0, deltaY = 0;
        final float viewWidth = getWidth();
        final float viewHeight = getHeight();
        // 推断移动或缩放后,图片显示是否超出裁剪框边界
        final float heightBorder = (viewHeight - borderlength) / 2;
        final float weightBorder = (viewWidth - borderlength) / 2;
        if(rect.top > heightBorder){
            deltaY = heightBorder - rect.top;
        }
        if(rect.bottom < (viewHeight - heightBorder)){
            deltaY = viewHeight - heightBorder - rect.bottom;
        }
        if(rect.left > weightBorder){
            deltaX = weightBorder - rect.left;
        }
        if(rect.right < viewWidth - weightBorder){
            deltaX = viewWidth - weightBorder - rect.right;
        }
        // Finally actually translate the matrix
        dragMatrix.postTranslate(deltaX, deltaY);

    }

    /**
     * 获取图片相对Matrix的距离
     *
     * @param matrix
     *            - Matrix to map Drawable against
     * @return RectF - Displayed Rectangle
     */
    private RectF getDisplayRect(Matrix matrix) {
        Drawable d = getDrawable();
        if (null != d) {
            displayRect.set(0, 0, d.getIntrinsicWidth(), d.getIntrinsicHeight());
            matrix.mapRect(displayRect);
            return displayRect;
        }

        return null;
    }

    /**
     * 剪切图片,返回剪切后的bitmap对象
     *
     * @return
     */
    public Bitmap clip(){
        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bitmap);
        draw(canvas);
        return Bitmap.createBitmap(bitmap, (getWidth() - borderlength) / 2, (getHeight() - borderlength) / 2, borderlength, borderlength);
    }
}

代码下载:https://github.com/h3clikejava/AndroidClipSquare

时间: 2024-10-09 20:05:59

AndroidClipSquare安卓实现方形头像裁剪的相关文章

上传头像裁剪功能

我之前做项目的时候有需求是需要实现上传头像裁剪再上传到服务器,所以上网看了一下别人写的案例.方法.文章,浪费了1天的时间,最后才跌跌碰碰的终于写了出来. 现在给大家分享一下吧. 所用到的js文件 cropper.min.js, canvas-to-blob.js(这个是IE上需要用到的,不然会不支持转blob) jquery.min.js, bootstrap.min.js ajaxfileupload.js css文件 cropper.min.css,bootstrap.min.css htm

用JQuery仿造QQ头像裁剪功能

原文:用JQuery仿造QQ头像裁剪功能 最近工作真心忙碌,几乎没时间写博客.今天趁周末来仿一个QQ头像裁剪功能插件.效果如下: 所有文件都可在我的Github上下载,从头到尾从简到繁按步骤一共分了9个HTML文件,每个步骤文件里的注释都写的很清楚,故在本博客内不赘述. 原理: 主要是通过css的clip来裁剪图片可视区域,拖动剪裁窗口这里使用了JQ-UI的draggable插件(但是缩放没有,贪方便可以使用Resizable插件,但都用插件的话就没有研究的意义了). 缩放功能原理其实很简单,不

Android高仿微信头像裁剪

最近公司的APP很多用户反应无法上传头像,于是打算修改原来头像裁剪的代码.参考微信.QQ.唱吧头像裁剪的操作,决定就仿微信头像裁剪来上传用户头像,在Android大神鸿洋的一篇高仿微信头像的博客(博客地址结尾会贴出来)的基础上加了一些代码,加的代码主要增加如下的功能: 1.增加对大图的处理,缩放到我们裁剪框的大小. 2.裁剪后的图片保存到临时文件里,把临时文件的路径返回到需要处理的界面,因为在三星S4传byte数组返回数据时会闪退,传路径则正常. 3.对有些系统返回旋转过的图片进行处理. 这个功

springMVC 头像裁剪上传并等比压

第一次写头像裁剪上传,原本想着直接本地预览裁剪再上传,可是时间有限,jquery.jcrop貌似并没有对 假设是ie下图片预览效果是滤镜做的  做出对应处理,也没有时间去改;仅仅好将就一下先把图片上传上去再预览 1.先看一下我引入的js <script src="${adminBasePath}resources/js/jquery.1.8.3.js"></script> <script src="${adminBasePath}resource

音乐平台项目的几个问题总结(头像裁剪以及跨页面播放音乐)

关于头像裁剪 1.上传图片的裁剪,并没有采用后端裁剪,而采用前端裁剪,基于cropbox进行了修改 编码使用一个隐藏的input框存放 存放到数据库 2.本来想在后端解析base64编码重新生成文件,后来发现并没有必要,如果图片不是很大直接保存字符串到数据库就行了,这样还可以少一些http请求,不过缺点是Ie6不支持date:url的解析 3.图片变成base64编码之后,保存在数据库的字符长度高达16W 个字符,后来想办法改成jpeg+中等保存之后,长度变成3W,可以接受 下面从代码说起 界面

html5 canvas头像裁剪上传

效果: 在博客里有另一篇头像裁剪是用actionscript实现的头像裁剪上传,这里拥护html5,用canvas实现下.前两次的右键是为了说明不是用flash做的. 如果想要更严谨的,有技术支持的这个东西的话,可以用kissy的http://gallery.kissyui.com/imgcrop/2.0/guide/index.html. 原理很简单:裁剪框是用html做的,canvas的作用在于每次移动,变形后根据裁剪框的位置坐标以及大小,绘制图像的部分并缩放,还有绘制裁剪框区域外的灰色区域

java头像裁剪上传

原文:java头像裁剪上传 源代码下载地址:http://www.zuidaima.com/share/1550463771118592.htm jsp页面实现头像裁剪上传,带进度条,后台java接收 上传成功后

基于cropper和sweetalert的简单图片/头像裁剪上传

基本功能 前端基本样式: 进行图片裁剪及上传: 点击上传后,js会将截取到的数据转为图片数据利用ajax发送给后台进行存储.存储成功后,刷新前端页面,头像改变. 上传成功后:自动刷新网页,更改头像 基本工具 cropper是一个功能强大的jq插件,在指定图片img上添加裁剪框,并根据指定事件对图片按照裁剪框的大小进行裁剪. crepper还可以对定义图片翻转.放大.移动以及输出裁剪框位置的很多功能,由于此处只是用于头像上传,所以只使用了基本功能. cropper使用时需要用到jq2.0以上,所以

安卓开发——拍照、裁剪并保存为头像报错:裁剪图片无法保存的

在做学校大创项目的安卓开发时,需要从相册获取图片或者拍照,然后裁剪保存为头像.由于我是第一次弄安卓开发,也对Android现在越来越多的权限限制不了解,debug过程真的是异常心塞啊. 闲话不说(文末慢慢话痨),我开始是在网上找了一些代码打算用到项目上试试,但是连个拍照或者从相册选择图片都频繁报错(应该还是因为sd卡权限之类的吧),折腾了一晚上没有解决,第二天还是老老实实的看<第一行代码>,边学边写.在这里我简单梳理一下流程(关于裁剪后图片无法保存的问题的解释请直接跳到水平线之后): 调用手机