头像及封面的裁剪与预览

直接上代码里面有注释

启动Activity

package com.lei.CropImage;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.widget.Button;import com.lei.CropImage.util.CropRectImgActivity;import com.lei.CropImage.util.CropRoundImgActivity;/** * Created by renlei * DATE: 15-1-13 * Time: 上午11:17 */public class StartActivity extends Activity {    Button button;    Button roundButton;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.start);        button = (Button)findViewById(R.id.cliprectbtn);        button.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent intent= new Intent(StartActivity.this, CropRectImgActivity.class);                startActivity(intent);            }        });        roundButton = (Button)findViewById(R.id.cliroundbtn);        roundButton.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent intent = new Intent(StartActivity.this, CropRoundImgActivity.class);                startActivity(intent);            }        });    }}

Clipimageview

package com.lei.CropImage.util;import android.annotation.TargetApi;import android.content.Context;import android.graphics.*;import android.graphics.Bitmap.Config;import android.graphics.PorterDuff.Mode;import android.graphics.drawable.Drawable;import android.os.Build;import android.os.Build.VERSION;import android.os.Build.VERSION_CODES;import android.util.AttributeSet;import android.util.Log;import android.view.*;import android.view.ScaleGestureDetector.OnScaleGestureListener;import android.widget.ImageView;/** * 用于缩放裁剪的自定义ImageView视图 * --renlei * */public class ClipImageView extends ImageView implements View.OnTouchListener,        ViewTreeObserver.OnGlobalLayoutListener {    private static final int BORDERDISTANCE = ClipRoundView.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;///最小的缩放比,如果设置成1表示刚进来的图片不可以在缩小    private float minScale = DEFAULT_MIN_SCALE;    private float midScale = DEFAULT_MID_SCALE;    private float maxScale = DEFAULT_MAX_SCALE;    private MultiGestureDetector multiGestureDetector;    private int borderlength;///矩形线框的长度    private boolean isJusted;    private final Matrix baseMatrix = new Matrix();    private final Matrix drawMatrix = new Matrix();    private final Matrix suppMatrix = new Matrix();    private final RectF displayRect = new RectF();    private final float[] matrixValues = new float[9];    /**     * 水平方向与View的边距     */    private int mHorizontalPadding = 20;    /**     * 垂直方向与View的边距     */    private int mVerticalPadding;    public ClipImageView(Context context) {        this(context, null);    }    public ClipImageView(Context context, AttributeSet attr) {        this(context, attr, 0);    }    public ClipImageView(Context context, AttributeSet attr, int defStyle) {        super(context, attr, defStyle);        super.setScaleType(ImageView.ScaleType.MATRIX);        setOnTouchListener(this);        multiGestureDetector = new MultiGestureDetector(context);    }    /**     * 依据图片宽高比例,设置图像初始缩放等级和位置     */    private void configPosition() {        //当绘制时使用图片矩阵缩放        super.setScaleType(ImageView.ScaleType.MATRIX);        Drawable d = getDrawable();        if (d == null) {            return;        }        final float viewWidth = getWidth();        final float viewHeight = getHeight();        final int drawableWidth = d.getIntrinsicWidth();        final int drawableHeight = d.getIntrinsicHeight();        //实际裁剪的矩形的宽度(并不是白色的矩形线条)等于总长度减去左右边距        borderlength = (int) (viewWidth - BORDERDISTANCE * 2);        float scale = 1.0f;        /**         * 判断图片宽高比例,调整显示位置和缩放大小         */        // 图片宽度小于等于高度        if (drawableWidth <= drawableHeight) {            // 判断图片宽度是否小于边框, 缩放铺满裁剪边框            if (drawableWidth < borderlength) {                baseMatrix.reset();                scale = (float) borderlength / drawableWidth;                // 缩放                baseMatrix.postScale(scale, scale);            }        } else {// 图片宽度大于高度            //并且图片的高度是小于实际裁剪的矩形的宽度            if (drawableHeight < borderlength) {                baseMatrix.reset();                scale = (float) borderlength / drawableHeight;                // 缩放                baseMatrix.postScale(scale, scale);            }        }        // 移动居中        baseMatrix.postTranslate((viewWidth - drawableWidth * scale) / 2,                (viewHeight - drawableHeight * scale) / 2);        resetMatrix();        isJusted = true;    }    @Override    public boolean onTouch(View v, MotionEvent event) {        return multiGestureDetector.onTouchEvent(event);    }    private class MultiGestureDetector extends            GestureDetector.SimpleOnGestureListener implements            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 detector) {            float scale = getScale();            /**             * public float getScaleFactor ()             *  返回从前一个伸缩事件至当前伸缩事件的伸缩比率。该值定义为 (getCurrentSpan() / getPreviousSpan())。             *  返回值             *  当前伸缩比率.             *   (scale < maxScale && scaleFactor > 1.0f) || (scale > minScale && scaleFactor < 1.0f)判断该图片是否处于缩放范围             */            float scaleFactor = detector.getScaleFactor();            Log.d("renlei",scaleFactor+"");            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;                }                suppMatrix.postScale(scaleFactor, scaleFactor, getWidth() / 2,                        getHeight() / 2);                checkAndDisplayMatrix();            }            return true;        }        @Override        public boolean onScaleBegin(ScaleGestureDetector detector) {            return true;        }        @Override        public void onScaleEnd(ScaleGestureDetector detector) {        }        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_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) {                            suppMatrix.postTranslate(dx, dy);                            checkAndDisplayMatrix();                        }                        lastTouchX = x;                        lastTouchY = y;                        if (velocityTracker != null) {                            velocityTracker.addMovement(event);                        }                    }                    break;                }                case MotionEvent.ACTION_UP:                case MotionEvent.ACTION_CANCEL:                    lastPointerCount = 0;                    if (velocityTracker != null) {                        velocityTracker.recycle();                        velocityTracker = null;                    }                    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;            }        }        public void run() {            suppMatrix.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(ClipImageView.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;                suppMatrix.postScale(delta, delta, focalX, focalY);                checkAndDisplayMatrix();            }        }    }    @TargetApi(Build.VERSION_CODES.JELLY_BEAN)    private void postOnAnimation(View view, Runnable runnable) {        if (VERSION.SDK_INT >= 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() {        suppMatrix.getValues(matrixValues);        return matrixValues[Matrix.MSCALE_X];    }    @Override    public void onGlobalLayout() {        if (isJusted) {            return;        }        // 调整视图位置        configPosition();    }    @Override    protected void onAttachedToWindow() {        super.onAttachedToWindow();        getViewTreeObserver().addOnGlobalLayoutListener(this);    }    @SuppressWarnings("deprecation")    @Override    protected void onDetachedFromWindow() {        super.onDetachedFromWindow();        getViewTreeObserver().removeGlobalOnLayoutListener(this);    }    /**     * 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();        // 判断移动或缩放后,图片显示是否超出裁剪框边界        if (rect.top > (viewHeight - borderlength) / 2) {            deltaY = (viewHeight - borderlength) / 2 - rect.top;        }        if (rect.bottom < (viewHeight + borderlength) / 2) {            deltaY = (viewHeight + borderlength) / 2 - rect.bottom;        }        if (rect.left > (viewWidth - borderlength) / 2) {            deltaX = (viewWidth - borderlength) / 2 - rect.left;        }        if (rect.right < (viewWidth + borderlength) / 2) {            deltaX = (viewWidth + borderlength) / 2 - rect.right;        }        // Finally actually translate the matrix        suppMatrix.postTranslate(deltaX, deltaY);    }    /**     * Helper method that maps the supplied Matrix to the current Drawable     *     * @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;    }    /**     * Resets the Matrix back to FIT_CENTER, and then displays it.s     */    private void resetMatrix() {        if (suppMatrix == null) {            return;        }        suppMatrix.reset();        setImageMatrix(getDisplayMatrix());    }    protected Matrix getDisplayMatrix() {        drawMatrix.set(baseMatrix);        drawMatrix.postConcat(suppMatrix);        return drawMatrix;    }    /**     * 剪切图片,返回剪切后的bitmap对象     * 裁剪圆图像,根据需求,此时仍然让其裁剪成方形,只是多了一个蒙层     * @return     */    public Bitmap clipRound() {        int width = this.getWidth();        int height = this.getHeight();        Bitmap bitmap = Bitmap.createBitmap(width, height,                Bitmap.Config.ARGB_8888);        Canvas canvas = new Canvas(bitmap);        draw(canvas);        return toRoundBitmap(Bitmap.createBitmap(bitmap,                (getWidth() - borderlength) / 2,                (getHeight() - borderlength) / 2, borderlength, borderlength));    }    /**     * 剪切图片,返回剪切后的bitmap对象     *     * @return     */    public Bitmap clipRect()    {        Bitmap bitmap = Bitmap.createBitmap(getWidth(), getHeight(),                Bitmap.Config.ARGB_8888);        Canvas canvas = new Canvas(bitmap);        draw(canvas);        //计算距离屏幕垂直边界 的边距        mVerticalPadding = (getHeight() - getWidth()) / 2;        return Bitmap.createBitmap(bitmap,                (getWidth() - borderlength) / 2,                (getHeight() - borderlength) / 2, borderlength, borderlength);    }    /**     * 转换图片成圆形     *     * @param bitmap     *            传入Bitmap对象     * @return     */    public Bitmap toRoundBitmap(Bitmap bitmap) {        int width = bitmap.getWidth();        int height = bitmap.getHeight();        float roundPx;        float left, top, right, bottom, dst_left, dst_top, dst_right, dst_bottom;        if (width <= height) {            roundPx = width / 2;            top = 0;            bottom = width;            left = 0;            right = width;            height = width;            dst_left = 0;            dst_top = 0;            dst_right = width;            dst_bottom = width;        } else {            roundPx = height / 2;            float clip = (width - height) / 2;            left = clip;            right = width - clip;            top = 0;            bottom = height;            width = height;            dst_left = 0;            dst_top = 0;            dst_right = height;            dst_bottom = height;        }        Bitmap output = Bitmap.createBitmap(width, height, Config.ARGB_8888);        Canvas canvas = new Canvas(output);        final int color = 0xff424242;        final Paint paint = new Paint();        final Rect src = new Rect((int) left, (int) top, (int) right,                (int) bottom);        final Rect dst = new Rect((int) dst_left, (int) dst_top,                (int) dst_right, (int) dst_bottom);        final RectF rectF = new RectF(dst);        paint.setAntiAlias(true);        canvas.drawARGB(0, 0, 0, 0);        paint.setColor(color);        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));        canvas.drawBitmap(bitmap, src, dst, paint);        return output;    }}

ClipRectView

package com.lei.CropImage.util;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.util.TypedValue;import android.view.View;/** * Created by renlei * DATE: 14-12-23 * Time: 上午11:22 * 主要是用来绘制裁剪区域的 */public class ClipRectView extends View {    /**     * 边框距左右边界距离,用于调整边框长度     */    public static final int BORDERDISTANCE = 50;    private Paint mPaint;    private Context mmContext;    /**     * 水平方向与View的边距     */    private int mHorizontalPadding = 30;    /**     * 垂直方向与View的边距     */    private int mVerticalPadding;    /**     * 绘制的矩形的宽度     */    private int mWidth;    /**     * 边框的颜色,默认为白色     */    private int mBorderColor = Color.parseColor("#FFFFFF");    /**     * 边框的宽度 单位dp     */    private int mBorderWidth = 1;    public ClipRectView(Context context) {        this(context, null);        this.mmContext = context;    }    public ClipRectView(Context context, AttributeSet attrs) {        this(context, attrs, 0);        this.mmContext = context;    }    public ClipRectView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        mmContext = context;        // 计算padding的px        mHorizontalPadding = (int) TypedValue.applyDimension(                TypedValue.COMPLEX_UNIT_DIP, mHorizontalPadding, getResources()                        .getDisplayMetrics());        mBorderWidth = (int) TypedValue.applyDimension(                TypedValue.COMPLEX_UNIT_DIP, mBorderWidth, getResources()                        .getDisplayMetrics());        mPaint = new Paint();        mPaint.setAntiAlias(true);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        //计算矩形区域的宽度        mWidth = getWidth() - 2 * mHorizontalPadding;        //计算距离屏幕垂直边界 的边距        mVerticalPadding = (getHeight() - mWidth) / 2;        mPaint.setColor(Color.parseColor("#aa000000"));        mPaint.setStyle(Paint.Style.FILL);        // 绘制左边1        /**         * drawRect:canvas.drawRect(left, top, right, bottom, paint)         这里的left、top、right、bottom的值是:         left:是矩形距离左边的X轴         top:是矩形距离上边的Y轴         right:是矩形的右边距离x轴的距离         bottom:是矩形下边距离y轴的距离         即         矩形的高 height = bottom  - top         矩形的宽 width  = right – left         下面的这四个函数其实是绘制的阴影部分,即遮罩部分,注意不要重叠绘制,不然效果会进行叠加         --renlei         */        canvas.drawRect(0, 0, mHorizontalPadding, getHeight(), mPaint);        // 绘制右边2        canvas.drawRect(getWidth() - mHorizontalPadding, 0, getWidth(),                getHeight(), mPaint);        // 绘制上边3        canvas.drawRect(mHorizontalPadding, 0, getWidth() - mHorizontalPadding,                mVerticalPadding, mPaint);        // 绘制下边4        canvas.drawRect(mHorizontalPadding, getHeight() - mVerticalPadding,                getWidth() - mHorizontalPadding, getHeight(), mPaint);        // 绘制外边框        mPaint.setColor(mBorderColor);        mPaint.setStrokeWidth(mBorderWidth);        mPaint.setStyle(Paint.Style.STROKE);        canvas.drawRect(mHorizontalPadding, mVerticalPadding, getWidth()                - mHorizontalPadding, getHeight() - mVerticalPadding, mPaint);    }    /* 根据手机的分辨率从 dp 的单位 转成为 px(像素) */    public static int dip2px(Context context, float dpValue) {        final float scale = context.getResources().getDisplayMetrics().density;        return (int) (dpValue * scale + 0.5f);    }}

ClipRoundView

package com.lei.CropImage.util;import android.content.Context;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.Paint;import android.util.AttributeSet;import android.view.View;/** * 裁剪边框 * --renlei */public class ClipRoundView extends View {    /**     * 边框距左右边界距离,用于调整边框长度     */    public static final int BORDERDISTANCE = 50;    private Paint mPaint;    private Context mContext;    public ClipRoundView(Context context) {        this(context, null);        mContext = context;    }    public ClipRoundView(Context context, AttributeSet attrs) {        this(context, attrs, 0);        mContext = context;    }    public ClipRoundView(Context context, AttributeSet attrs, int defStyle) {        super(context, attrs, defStyle);        mContext = context;        mPaint = new Paint();    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        int width = this.getWidth();        int height = this.getHeight();        int innerCircle = dip2px(mContext, 150); // 内圆半径        int ringWidth = height; // 圆环宽度        // 第一种方法绘制圆环false        // 绘制内圆        mPaint.setColor(Color.WHITE);        mPaint.setStrokeWidth(2);        mPaint.setStyle(Paint.Style.STROKE);        mPaint.setAntiAlias(true);//消除锯齿        mPaint.setFilterBitmap(true);        /**         * cx:圆心的x坐标。         cy:圆心的y坐标。         radius:圆的半径。         paint:绘制时所使用的画笔。         */        canvas.drawCircle(width / 2, height / 2, innerCircle, mPaint);        // 绘制圆环        mPaint.setColor(0xaa000000);        mPaint.setStrokeWidth(ringWidth);        canvas.drawCircle(width / 2, height / 2, innerCircle + 1 + ringWidth                / 2, mPaint);    }    /* 根据手机的分辨率从 dp 的单位 转成为 px(像素) */    public static int dip2px(Context context, float dpValue) {        final float scale = context.getResources().getDisplayMetrics().density;        return (int) (dpValue * scale + 0.5f);    }}

CropRectActivity

package com.lei.CropImage.util;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.graphics.Bitmap;import android.os.Bundle;import android.view.View;import android.view.inputmethod.InputMethodManager;import android.widget.TextView;import com.lei.CropImage.MyActivity;import com.lei.CropImage.R;import java.io.ByteArrayOutputStream;/** * Created by renlei * DATE: 14-12-22 * Time: 下午2:36 * 裁剪成方图片 */public class CropRectImgActivity extends Activity{    private ClipImageView cropIV;    private TextView saveTextView;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.setting_crop_rectimage_layout);        cropIV = (ClipImageView)findViewById(R.id.clip_cover_imageview);        saveTextView = (TextView)findViewById(R.id.rectimg_finish);        initView();    }    public void initView(){//        cropIV.loadImage(url);        cropIV.setImageResource(R.drawable.common_default_cover);        saveTextView.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                onSaveClick(v);            }        });    }    public void onSaveClick(View v){        ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);        Bitmap bitmap = cropIV.clipRect();        // 由于Intent传递bitmap不能超过40k,此处使用二进制数组传递        ByteArrayOutputStream baos = new ByteArrayOutputStream();        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);        byte[] bitmapByte = baos.toByteArray();        Intent intent = new Intent(CropRectImgActivity.this, MyActivity.class);        Bundle bundle = new Bundle();        bundle.putByteArray("bitmap", bitmapByte);        intent.putExtras(bundle);        startActivity(intent);    }}

CropRoundImgActivity

package com.lei.CropImage.util;import android.app.Activity;import android.app.Fragment;import android.content.Context;import android.content.Intent;import android.graphics.Bitmap;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.inputmethod.InputMethodManager;import android.widget.TextView;import com.lei.CropImage.MyActivity;import com.lei.CropImage.R;import java.io.ByteArrayOutputStream;/** * Created by renlei * DATE: 14-12-22 * Time: 下午2:36 * Email: lei.ren@renren-inc.com * 裁剪成圆头像 */public class CropRoundImgActivity extends Activity{    private ClipImageView cropIV;    private TextView saveTextView;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.setting_crop_roundimage_layout);        initView();    }    public void initView(){        cropIV = (ClipImageView)findViewById(R.id.clip_imageview);//        cropIV.loadImage(url);        cropIV.setImageResource(R.drawable.common_default_cover);        saveTextView = (TextView)findViewById(R.id.roundimg_finish);        saveTextView.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                onSaveClick(v);            }        });    }    public void onSaveClick(View v){        ((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(v.getWindowToken(), 0);        Bitmap bitmap = cropIV.clipRound();        // 由于Intent传递bitmap不能超过40k,此处使用二进制数组传递        ByteArrayOutputStream baos = new ByteArrayOutputStream();        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);        byte[] bitmapByte = baos.toByteArray();        Intent intent = new Intent(CropRoundImgActivity.this, MyActivity.class);        Bundle bundle = new Bundle();        bundle.putByteArray("bitmap", bitmapByte);        intent.putExtras(bundle);        startActivity(intent);        //下面是将其传递走了,这里只预览一下了      /*  byte[] bitmapByte = baos.toByteArray();        Methods.logInfo("renlei size round",bitmapByte.length+"");        Intent intent = new Intent(getActivity(), SettingEditProfileFragment.class);        headBytes = bitmapByte;        if (headBytes.length>0){            intent.putExtra(CROP_IMAGE_BYTE_URL,HAS_URL);        }else {            intent.putExtra(CROP_IMAGE_BYTE_URL,NO_URL);        }        getActivity().setResult(Activity.RESULT_OK,intent);        getActivity().finish();*/    }}

预览页面

package com.lei.CropImage;import android.app.Activity;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.os.Bundle;import android.widget.ImageView;public class MyActivity extends Activity {    /**     * Called when the activity is first created.     */    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        setTitle("预览");        ImageView imageView = (ImageView) findViewById(R.id.preview);        byte[] bis = getIntent().getByteArrayExtra("bitmap");        Bitmap bitmap = BitmapFactory.decodeByteArray(bis, 0, bis.length);        if(bitmap != null){            imageView.setImageBitmap(bitmap);        }    }}

裁剪方形的xml

<?xml version="1.0" encoding="utf-8"?>            

裁剪圆形的xml

<?xml version="1.0" encoding="utf-8"?>            

下载地址

http://download.csdn.net/detail/renlei0109/8356467