热门标签 | HotTags
当前位置:  开发笔记 > Android > 正文

Android以任意比例裁剪图片代码分享

这篇文章主要介绍了Android以任意比例裁剪图片的相关资料,非货不错,具有参考借鉴价值,需要的朋友可以参考下

公司的一个小伙伴写的,可以按照任意比例裁剪图片。我觉得挺好用的。简单在这里记录一下,以后肯定还会用到。

public class SeniorCropImageView extends ImageView implements ScaleGestureDetector.OnScaleGestureListener, 
View.OnLayoutChangeListener { 
/* For drawing color field start */ 
private static final int LINE_COLOR = Color.WHITE; 
private static final int OUTER_MASK_COLOR = Color.argb(191, 0, 0, 0); 
private static final int LINE_WIDTH_IN_DP = 1; 
private final float[] mMatrixValues = new float[9]; 
protected Matrix mSupportMatrix; 
protected ScaleGestureDetector mScaleGestureDetector; 
/* For drawing color field end */ 
protected Paint mPaint; 
/* 
* 宽比高 
*/ 
protected float mRatio = 1.0f; 
protected RectF mCropRect; 
//RectFPadding是适应产品需求,给裁剪框mCropRect设置一下padding -- chenglin 2016年04月18日 
protected float RectFPadding = 0; 
protected int mLastX; 
protected int mLastY; 
protected OPERATION mOperation; 
private onBitmapLoadListener iBitmapLoading = null; 
private boolean mEnableDrawCropWidget = true; 
/* 
For scale and drag 
*/ 
private Matrix mBaseMatrix; 
private Matrix mDrawMatrix; 
private AccelerateDecelerateInterpolator sInterpolator = new AccelerateDecelerateInterpolator(); 
private Path mPath; 
private int mLineWidth; 
private float mScaleMax = 3.0f; 
private RectF mBoundaryRect; 
private int mRotation = 0; 
private int mImageWidth; 
private int mImageHeight; 
private int mDisplayW; 
private int mDisplayH; 
public SeniorCropImageView(Context context) { 
this(context, null); 
} 
public SeniorCropImageView(Context context, AttributeSet attrs) { 
this(context, attrs, 0); 
} 
public SeniorCropImageView(Context context, AttributeSet attrs, int defStyleAttr) { 
super(context, attrs, defStyleAttr); 
if (attrs != null) { 
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Life_CropImage); 
mRatio = a.getFloat(R.styleable.Life_CropImage_life_Crop_ratio, 1.0f); 
a.recycle(); 
} 
init(); 
} 
public static void decodeImageForCropping(final String path, final IDecodeCallback callback) { 
new Thread(new Runnable() { 
@Override 
public void run() { 
int rotation = 0; 
// 读取一下exif中的rotation 
try { 
ExifInterface exif = new ExifInterface(path); 
final int rotate = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_UNDEFINED); 
switch (rotate) { 
case ExifInterface.ORIENTATION_ROTATE_90: 
rotation = 90; 
break; 
case ExifInterface.ORIENTATION_ROTATE_180: 
rotation = 180; 
break; 
case ExifInterface.ORIENTATION_ROTATE_270: 
rotation = 270; 
break; 
} 
} catch (IOException e) { 
e.printStackTrace(); 
} 
final BitmapFactory.Options optiOns= new BitmapFactory.Options(); 
options.inJustDecodeBounds = true; 
BitmapFactory.decodeFile(path, options); 
final int textureLimit = getMaxTextureSize(); 
int scale = 1; 
while (options.outWidth / scale >= textureLimit) { 
scale *= 2; 
} 
while (options.outHeight / scale >= textureLimit) { 
scale *= 2; 
} 
options.inSampleSize = scale; 
options.inJustDecodeBounds = false; 
Bitmap bitmap = null; 
try { 
bitmap = BitmapFactory.decodeFile(path, options); 
} catch (OutOfMemoryError e) { 
e.printStackTrace(); 
} 
final Bitmap bimapDecoded = bitmap; 
if (bimapDecoded == null) { 
return; 
} 
if (callback != null) { 
callback.onDecoded(rotation, bimapDecoded); 
} 
} 
}).start(); 
} 
private static int getMaxTextureSize() { 
EGL10 egl = (EGL10) EGLContext.getEGL(); 
EGLDisplay display = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); 
// Initialise 
int[] version = new int[2]; 
egl.eglInitialize(display, version); 
// Query total number of configurations 
int[] totalCOnfigurations= new int[1]; 
egl.eglGetConfigs(display, null, 0, totalConfigurations); 
// Query actual list configurations 
EGLConfig[] cOnfigurationsList= new EGLConfig[totalConfigurations[0]]; 
egl.eglGetConfigs(display, configurationsList, totalConfigurations[0], totalConfigurations); 
int[] textureSize = new int[1]; 
int maximumTextureSize = 0; 
// Iterate through all the configurations to located the maximum texture size 
for (int i = 0; i  mRatio; 
final int rectH = (int) (boundaryWidth / mRatio); 
final int rectW = (int) (boundaryHeight * mRatio); 
if (vertical) { 
left = (boundaryWidth - rectW) / 2; 
top = 0; 
right = (boundaryWidth + rectW) / 2; 
bottom = boundaryHeight; 
} else { 
left = 0; 
top = (boundaryHeight - rectH) / 2; 
right = boundaryWidth; 
bottom = (boundaryHeight + rectH) / 2; 
} 
//RectFPadding是适应产品需求,给裁剪框mCropRect设置一下padding -- chenglin 2016年04月18日 
mCropRect.set(left + RectFPadding, top + RectFPadding, right + RectFPadding, bottom + RectFPadding); 
} 
@Override 
protected void onDraw(Canvas canvas) { 
super.onDraw(canvas); 
if (!mEnableDrawCropWidget) { 
return; 
} 
if (getDrawable() == null) { 
return; 
} 
mPaint.reset(); 
mPaint.setAntiAlias(true); 
mPaint.setColor(LINE_COLOR); 
mPaint.setStrokeWidth(mLineWidth); 
mPaint.setStyle(Paint.Style.STROKE); 
mPath.reset(); 
// 上 
mPath.moveTo(mCropRect.left, mCropRect.top); 
mPath.lineTo(mCropRect.right, mCropRect.top); 
// 左 
mPath.moveTo(mCropRect.left, mCropRect.top); 
mPath.lineTo(mCropRect.left, mCropRect.bottom); 
// 右 
mPath.moveTo(mCropRect.right, mCropRect.top); 
mPath.lineTo(mCropRect.right, mCropRect.bottom); 
// 下 
mPath.moveTo(mCropRect.right, mCropRect.bottom); 
mPath.lineTo(mCropRect.left, mCropRect.bottom); 
canvas.drawPath(mPath, mPaint); 
// 绘制外部阴影部分 
mPaint.reset(); 
mPaint.setAntiAlias(true); 
mPaint.setColor(Color.parseColor("#B3333333")); 
mPaint.setStyle(Paint.Style.FILL); 
//下面的四个矩形是装饰性的,就是裁剪框四周的四个阴影 
final int lineOffset = mLineWidth; 
if (mCropRect.top > 0) { 
canvas.drawRect(0, 0, getMeasuredWidth(), mCropRect.top - lineOffset, mPaint); 
} 
if (mCropRect.left > 0) { 
canvas.drawRect(mCropRect.top - lineOffset - RectFPadding, RectFPadding - lineOffset, mCropRect.left - lineOffset, mCropRect.bottom + lineOffset, mPaint); 
} 
if (mCropRect.right  1) { 
mOperation = OPERATION.SCALE; 
return mScaleGestureDetector.onTouchEvent(ev); 
} 
final int action = ev.getActionMasked(); 
final int x = (int) ev.getX(); 
final int y = (int) ev.getY(); 
switch (action) { 
case MotionEvent.ACTION_DOWN: 
mOperation = OPERATION.DRAG; 
mLastX = x; 
mLastY = y; 
break; 
case MotionEvent.ACTION_MOVE: 
if (mOperation == OPERATION.DRAG) { 
int deltaX = x - mLastX; 
int deltaY = y - mLastY; 
RectF boundary = getDrawBoundary(getDrawMatrix()); 
if (boundary.left + deltaX > mCropRect.left) { 
deltaX = (int) (mCropRect.left - boundary.left); 
} else if (boundary.right + deltaX  mCropRect.top) { 
deltaY = (int) (mCropRect.top - boundary.top); 
} else if (boundary.bottom + deltaY  borderW) { 
cropRect.right = borderW; 
} 
if (cropRect.bottom > borderH) { 
cropRect.bottom = borderH; 
} 
} 
@Override 
public boolean onScale(ScaleGestureDetector detector) { 
float scale = detector.getScaleFactor(); 
if (scale == 1.0f) { 
return true; 
} 
final float currentScale = getScale(mSupportMatrix); 
final float centerX = detector.getFocusX(); 
final float centerY = detector.getFocusY(); 
if ((currentScale <= 1.0f && scale <1.0f) 
|| (currentScale >= mScaleMax && scale > 1.0f)) { 
return true; 
} 
if (currentScale * scale <1.0f) { 
scale = 1.0f / currentScale; 
} else if (currentScale * scale > mScaleMax) { 
scale = mScaleMax / currentScale; 
} 
mSupportMatrix.postScale(scale, scale, centerX, centerY); 
RectF boundary = getDrawBoundary(getDrawMatrix()); 
float translateX = 0; 
if (boundary.left > mCropRect.left) { 
translateX = mCropRect.left - boundary.left; 
} else if (boundary.right " + translateX); 
float translateY = 0; 
if (boundary.top > mCropRect.top) { 
translateY = mCropRect.top - boundary.top; 
} else if (boundary.bottom " + currentScale); 
RectF boundary = getDrawBoundary(getDrawMatrix()); 
post(new AnimatedZoomRunnable(currentScale, 1.0f, boundary.centerX(), boundary.centerY())); 
} 
} 
protected RectF getDrawBoundary(Matrix matrix) { 
Drawable drawable = getDrawable(); 
if (drawable == null) { 
return mBoundaryRect; 
} 
final int bitmapWidth = drawable.getIntrinsicWidth(); 
final int bitmapHeight = drawable.getIntrinsicHeight(); 
mBoundaryRect.set(0, 0, bitmapWidth, bitmapHeight); 
matrix.mapRect(mBoundaryRect); 
return mBoundaryRect; 
} 
public float getScale(Matrix matrix) { 
return (float) Math.sqrt((float) Math.pow(getValue(matrix, Matrix.MSCALE_X), 2) + (float) Math.pow(getValue(matrix, Matrix.MSKEW_Y), 2)); 
} 
/** 
* Helper method that 'unpacks' a Matrix and returns the required value 
* 
* @param matrix - Matrix to unpack 
* @param whichValue - Which value from Matrix.M* to return 
* @return float - returned value 
*/ 
private float getValue(Matrix matrix, int whichValue) { 
matrix.getValues(mMatrixValues); 
return mMatrixValues[whichValue]; 
} 
public void enableDrawCropWidget(boolean enable) { 
mEnableDrawCropWidget = enable; 
} 
protected enum OPERATION { 
DRAG, SCALE 
} 
public enum Type { 
CENTER_CROP, CENTER_INSIDE 
} 
public interface IDecodeCallback { 
void onDecoded(final int rotation, final Bitmap bitmap); 
} 
//setImagePath这个方法耗时,需要显示进度条,这个是监听 
public interface onBitmapLoadListener { 
void onLoadPrepare(); 
void onLoadFinish(); 
} 
private class AnimatedZoomRunnable implements Runnable { 
private final float mFocalX, mFocalY; 
private final long mStartTime; 
private final float mZoomStart, mZoomEnd; 
public AnimatedZoomRunnable(final float currentZoom, final float targetZoom, 
final float focalX, final float focalY) { 
mFocalX = focalX; 
mFocalY = focalY; 
mStartTime = System.currentTimeMillis(); 
mZoomStart = currentZoom; 
mZoomEnd = targetZoom; 
} 
@Override 
public void run() { 
float t = interpolate(); 
float scale = mZoomStart + t * (mZoomEnd - mZoomStart); 
float deltaScale = scale / getScale(mSupportMatrix); 
mSupportMatrix.postScale(deltaScale, deltaScale, mFocalX, mFocalY); 
setImageMatrix(getDrawMatrix()); 
// We haven't hit our target scale yet, so post ourselves again 
if (t <1f) { 
postOnAnimation(this); 
} 
} 
private float interpolate() { 
float t = 1f * (System.currentTimeMillis() - mStartTime) / 200; 
t = Math.min(1f, t); 
t = sInterpolator.getInterpolation(t); 
return t; 
} 
} 
} 
 
 
 
 
 
 

1、让这个裁剪框显示图片:

mSeniorImageView.setImagePath(path);

2、保存裁剪后的图片:

Bitmap imageViewBitmap = null; 
try { 
imageViewBitmap = mSeniorImageView.saveCrop(); 
} catch (OutOfMemoryError e) { 
imageViewBitmap = mSeniorImageView.getOriginBitmap(); 
PinkToast.makeText(mActivity, R.string.life_image_crop_topbar_crop_error, Toast.LENGTH_LONG).show(); 
}

3、设置裁剪比例:

mSeniorImageView.setCropRatio(3f / 4f);

4、设置裁剪框的padding:

mSeniorImageView.setCropRectPadding(0f);

5、setImagePath这个方法比较耗时,需要显示进度条,这个是监听:

mSeniorImageView.setBitmapLoadingListener(new SeniorCropImageView.onBitmapLoadListener() { 
@Override 
public void onLoadPrepare() { 
mActivity.showProgress(); 
} 
@Override 
public void onLoadFinish() { 
mActivity.hideProgress(); 
} 
});

以上所述是小编给大家带来的Android 以任意比例裁剪图片代码分享,希望对大家有所帮助


推荐阅读
  • Monkey《大话移动——Android与iOS应用测试指南》的预购信息发布啦!
    Monkey《大话移动——Android与iOS应用测试指南》的预购信息已经发布,可以在京东和当当网进行预购。感谢几位大牛给出的书评,并呼吁大家的支持。明天京东的链接也将发布。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • android listview OnItemClickListener失效原因
    最近在做listview时发现OnItemClickListener失效的问题,经过查找发现是因为button的原因。不仅listitem中存在button会影响OnItemClickListener事件的失效,还会导致单击后listview每个item的背景改变,使得item中的所有有关焦点的事件都失效。本文给出了一个范例来说明这种情况,并提供了解决方法。 ... [详细]
  • 本文讨论了Alink回归预测的不完善问题,指出目前主要针对Python做案例,对其他语言支持不足。同时介绍了pom.xml文件的基本结构和使用方法,以及Maven的相关知识。最后,对Alink回归预测的未来发展提出了期待。 ... [详细]
  • 本文讨论了如何优化解决hdu 1003 java题目的动态规划方法,通过分析加法规则和最大和的性质,提出了一种优化的思路。具体方法是,当从1加到n为负时,即sum(1,n)sum(n,s),可以继续加法计算。同时,还考虑了两种特殊情况:都是负数的情况和有0的情况。最后,通过使用Scanner类来获取输入数据。 ... [详细]
  • 本文讲述了如何通过代码在Android中更改Recycler视图项的背景颜色。通过在onBindViewHolder方法中设置条件判断,可以实现根据条件改变背景颜色的效果。同时,还介绍了如何修改底部边框颜色以及提供了RecyclerView Fragment layout.xml和项目布局文件的示例代码。 ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文介绍了OC学习笔记中的@property和@synthesize,包括属性的定义和合成的使用方法。通过示例代码详细讲解了@property和@synthesize的作用和用法。 ... [详细]
  • Mac OS 升级到11.2.2 Eclipse打不开了,报错Failed to create the Java Virtual Machine
    本文介绍了在Mac OS升级到11.2.2版本后,使用Eclipse打开时出现报错Failed to create the Java Virtual Machine的问题,并提供了解决方法。 ... [详细]
  • 在说Hibernate映射前,我们先来了解下对象关系映射ORM。ORM的实现思想就是将关系数据库中表的数据映射成对象,以对象的形式展现。这样开发人员就可以把对数据库的操作转化为对 ... [详细]
  • baresip android编译、运行教程1语音通话
    本文介绍了如何在安卓平台上编译和运行baresip android,包括下载相关的sdk和ndk,修改ndk路径和输出目录,以及创建一个c++的安卓工程并将目录考到cpp下。详细步骤可参考给出的链接和文档。 ... [详细]
  • 【Windows】实现微信双开或多开的方法及步骤详解
    本文介绍了在Windows系统下实现微信双开或多开的方法,通过安装微信电脑版、复制微信程序启动路径、修改文本文件为bat文件等步骤,实现同时登录两个或多个微信的效果。相比于使用虚拟机的方法,本方法更简单易行,适用于任何电脑,并且不会消耗过多系统资源。详细步骤和原理解释请参考本文内容。 ... [详细]
  • Android Studio Bumblebee | 2021.1.1(大黄蜂版本使用介绍)
    本文介绍了Android Studio Bumblebee | 2021.1.1(大黄蜂版本)的使用方法和相关知识,包括Gradle的介绍、设备管理器的配置、无线调试、新版本问题等内容。同时还提供了更新版本的下载地址和启动页面截图。 ... [详细]
  • 本文介绍了在SpringBoot中集成thymeleaf前端模版的配置步骤,包括在application.properties配置文件中添加thymeleaf的配置信息,引入thymeleaf的jar包,以及创建PageController并添加index方法。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
author-avatar
佳鈺佳琴欣怡
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有