传入任意形状的bitmap,输出圆形Bitmap供显示
public Bitmap createCircularBitmap(Bitmap input, int width, int height) {
if (input == null)
return null;
final int inWidth = input.getWidth();
final int inHeight = input.getHeight();
final Bitmap output = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(output);
final Paint paint = new Paint();
paint.setShader(new BitmapShader(input, Shader.TileMode.CLAMP,
Shader.TileMode.CLAMP));
paint.setAntiAlias(true);
final RectF srcRect = new RectF(0, 0, inWidth, inHeight);
final RectF dstRect = new RectF(0, 0, width, height);
final Matrix m = new Matrix();
m.setRectToRect(srcRect, dstRect, Matrix.ScaleToFit.CENTER);
canvas.setMatrix(m);
canvas.drawCircle(inWidth / 2, inHeight / 2, inWidth / 2, paint);
return output;
}
public static Bitmap resizeBitmapByScale(Bitmap bitmap, float scale,
boolean recycle) {
int width = Math.round(bitmap.getWidth() * scale);
int height = Math.round(bitmap.getHeight() * scale);
if (width == bitmap.getWidth() && height == bitmap.getHeight())
return bitmap;
Bitmap target = Bitmap.createBitmap(width, height,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(target);
canvas.scale(scale, scale);
Paint paint = new Paint(Paint.FILTER_BITMAP_FLAG | Paint.DITHER_FLAG);
canvas.drawBitmap(bitmap, 0, 0, paint);
if (recycle)
bitmap.recycle();
return target;
}
传入角度值,输出旋转后的Bitmap供显示,这里角度值不能是360的整数倍,求余运算排除此种情况。
public static Bitmap rotateBitmap(Bitmap source, int rotation,
boolean recycle) {
if (rotation % 360 == 0 || source == null)
return source;
int w = source.getWidth();
int h = source.getHeight();
Matrix m = new Matrix();
m.postRotate(rotation);
Bitmap bitmap = Bitmap.createBitmap(source, 0, 0, w, h, m, true);
if (recycle)
source.recycle();
return bitmap;
}
有时需要将Bitmap转字节数组方便传输或存储,可以采用以下代码片段。
/**
* @param bitmap bitmap输入源
* @param quality 压缩质量,取值范围在0~100之间,
* @return 包含Bitmap信息的byte数组
*/
public static byte[] compressToBytes(Bitmap bitmap, int quality) {
ByteArrayOutputStream baos = new ByteArrayOutputStream(65536);
bitmap.compress(CompressFormat.JPEG, quality, baos);
return baos.toByteArray();
}
反之如果需要将存储了Bitmap信息的字节数组转成Bitmap则可以用BitmapFactory里面的decodeByteArray(byte[] data, int offset, int length, Options opts)
方法。