Android实现Bitmap位图旋转效果

时间:2021-05-19

位图的旋转也可以借助Matrix或者Canvas来实现。

通过postRotate方法设置旋转角度,然后用createBitmap方法创建一个经过旋转处理的Bitmap对象,最后用drawBitmap方法绘制到屏幕上,于是就实现了旋转操作。

下面例子中把原位图和经旋转处理的位图都绘制到屏幕上,目的是做一个对比。

package xiaosi.bitmap; import android.app.Activity; import android.os.Bundle; public class mianActivity extends Activity { private BitmapView bitmapView = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); bitmapView = new BitmapView(this); setContentView(bitmapView); } }

BitmapView.Java

package xiaosi.bitmap; import android.content.Context; import android.content.res.Resources; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Matrix; import android.view.View; public class BitmapView extends View { public BitmapView(Context context) { super(context); } //重写onDraw方法 public void onDraw(Canvas canvas) { // 获取资源文件的引用res Resources res = getResources(); // 获取图形资源文件 Bitmap bmp = BitmapFactory.decodeResource(res, R.drawable.h); // 设置canvas画布背景为白色 canvas.drawColor(Color.BLACK); // 在画布上绘制缩放之前的位图,以做对比 //屏幕上的位置坐标是0,0 canvas.drawBitmap(bmp, 0, 0, null); // 定义矩阵对象 Matrix matrix = new Matrix(); // 缩放原图 matrix.postScale(1f, 1f); // 向左旋转45度,参数为正则向右旋转 matrix.postRotate(-45); //bmp.getWidth(), 500分别表示重绘后的位图宽高 Bitmap dstbmp = Bitmap.createBitmap(bmp, 0, 0, bmp.getWidth(), 500, matrix, true); // 在画布上绘制旋转后的位图 //放在坐标为0,200的位置 canvas.drawBitmap(dstbmp, 0, 200, null); } }

源代码下载:点击打开链接

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。

声明:本页内容来源网络,仅供用户参考;我单位不保证亦不表示资料全面及准确无误,也不保证亦不表示这些资料为最新信息,如因任何原因,本网内容或者用户因倚赖本网内容造成任何损失或损害,我单位将不会负任何法律责任。如涉及版权问题,请提交至online#300.cn邮箱联系删除。

相关文章