本文主要是介绍Android Bitmap转换操作:缩放、裁剪、旋转、偏移,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
原文链接
/*** 根据给定的宽和高进行拉伸** @param origin 原图* @param newWidth 新图的宽* @param newHeight 新图的高* @return new Bitmap*/private Bitmap scaleBitmap(Bitmap origin, int newWidth, int newHeight) {if (origin == null) {return null;}int height = origin.getHeight();int width = origin.getWidth();float scaleWidth = ((float) newWidth) / width;float scaleHeight = ((float) newHeight) / height;Matrix matrix = new Matrix();matrix.postScale(scaleWidth, scaleHeight);// 使用后乘Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);if (!origin.isRecycled()) {origin.recycle();}return newBM;}/*** 按比例缩放图片** @param origin 原图* @param ratio 比例* @return 新的bitmap*/private Bitmap scaleBitmap(Bitmap origin, float ratio) {if (origin == null) {return null;}int width = origin.getWidth();int height = origin.getHeight();Matrix matrix = new Matrix();matrix.preScale(ratio, ratio);Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);if (newBM.equals(origin)) {return newBM;}origin.recycle();return newBM;}/*** 裁剪** @param bitmap 原图* @return 裁剪后的图像*/private Bitmap cropBitmap(Bitmap bitmap) {int w = bitmap.getWidth(); // 得到图片的宽,高int h = bitmap.getHeight();int cropWidth = w >= h ? h : w;// 裁切后所取的正方形区域边长cropWidth /= 2;int cropHeight = (int) (cropWidth / 1.2);return Bitmap.createBitmap(bitmap, w / 3, 0, cropWidth, cropHeight, null, false);}/*** 选择变换** @param origin 原图* @param alpha 旋转角度,可正可负* @return 旋转后的图片*/private Bitmap rotateBitmap(Bitmap origin, float alpha) {if (origin == null) {return null;}int width = origin.getWidth();int height = origin.getHeight();Matrix matrix = new Matrix();matrix.setRotate(alpha);// 围绕原地进行旋转Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);if (newBM.equals(origin)) {return newBM;}origin.recycle();return newBM;}/*** 偏移效果* @param origin 原图* @return 偏移后的bitmap*/private Bitmap skewBitmap(Bitmap origin) {if (origin == null) {return null;}int width = origin.getWidth();int height = origin.getHeight();Matrix matrix = new Matrix();matrix.postSkew(-0.6f, -0.3f);Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false);if (newBM.equals(origin)) {return newBM;}origin.recycle();return newBM;}
这篇关于Android Bitmap转换操作:缩放、裁剪、旋转、偏移的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!