简书链接:bitmap旋转平移有效的样板代码
文章字数:251,阅读全文大约需要1分钟
哎、不服老不行了,现在基础都给搞懵逼了。
bitmap旋转90 ,测试是居中旋转的,之前不是距中旋转的代码我有空看看比较下。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public static 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; }
|
平移代码 如果设置画笔则能看到移动后被挪开的背景颜色
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| /** * 平移代码 * @param origin * @param x * @param y * @return */ public static Bitmap translateBitmap(Bitmap origin, float x,float y) { // Bitmap returnBitmap = Bitmap.createBitmap(origin,0,0,origin.getWidth(),origin.getHeight()); Bitmap returnBitmap = Bitmap.createBitmap(origin.getWidth(),origin.getHeight(), Bitmap.Config.ARGB_8888); Canvas canvas=new Canvas(returnBitmap); //2.设置画笔 // Paint paint=new Paint(); // paint.setColor(Color.BLACK); // canvas.drawColor(Color.WHITE); // paint.setAntiAlias(true); //消除锯齿 //3.画位图
Matrix matrix=new Matrix(); matrix.postTranslate(x, y); canvas.drawBitmap(origin,matrix, null);
return returnBitmap;
|
平移下面这样写无法平移没有效果的 ,目前没搞懂原因,可能是要进行所谓的其他缩放等操作,百思不得其解,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| public static Bitmap rotateBitmap(Bitmap origin, float x,float y) { if (origin == null) { return null; } int width = origin.getWidth(); int height = origin.getHeight(); Matrix matrix = new Matrix(); matrix.postTranslate(x,y); // 围绕原地进行旋转 Bitmap newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false); if (newBM.equals(origin)) { return newBM; } origin.recycle(); return newBM; }
|
之前可能是即时运行问题现在又可以了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| public static Bitmap adjustPhotoRotation(Bitmap bm, final int orientationDegree) {
Matrix m = new Matrix(); m.setRotate(orientationDegree, (float) bm.getWidth() / 2, (float) bm.getHeight() / 2); float targetX, targetY; if (orientationDegree == 90) { targetX = bm.getHeight(); targetY = 0; } else { targetX = bm.getHeight(); targetY = bm.getWidth(); }
final float[] values = new float[9]; m.getValues(values);
float x1 = values[Matrix.MTRANS_X]; float y1 = values[Matrix.MTRANS_Y];
m.postTranslate(targetX - x1, targetY - y1);
Bitmap bm1 = Bitmap.createBitmap(bm.getHeight(), bm.getWidth(), Bitmap.Config.ARGB_8888);
Paint paint = new Paint(); Canvas canvas = new Canvas(bm1); canvas.drawBitmap(bm, m, paint);
return bm1; }
|