Activity_main.xml文件配置
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:orientation="vertical" tools:context=".MainActivity" > <ImageView android:id="@+id/iv_src" android:layout_width="wrap_content" android:layout_height="wrap_content" /> <ImageView android:id="@+id/iv_rotate" android:layout_width="wrap_content" android:layout_height="wrap_content" /> </LinearLayout>
MainActivity.java代码
1 package com.imagerotota.view; 2 3 import android.app.Activity; 4 import android.graphics.Bitmap; 5 import android.graphics.BitmapFactory; 6 import android.graphics.Canvas; 7 import android.graphics.Matrix; 8 import android.graphics.Paint; 9 import android.os.Bundle; 10 import android.os.SystemClock; 11 import android.widget.ImageView; 12 13 public class MainActivity extends Activity { 14 15 private ImageView ivSrc; 16 private ImageView ivRatate; 17 18 @Override 19 protected void onCreate(Bundle savedInstanceState) { 20 super.onCreate(savedInstanceState); 21 setContentView(R.layout.activity_main); 22 // 获取图片中相应的控件 23 ivSrc = (ImageView) findViewById(R.id.iv_src); 24 ivRatate = (ImageView) findViewById(R.id.iv_rotate); 25 // 将src.jpg图片转换为Bitmap 26 final Bitmap srcBitmap = BitmapFactory.decodeResource(getResources(),R.drawable.src); 27 // 在原图BitMap中不能对图片进行修改,只能复制图片中进行修改 28 // srcBitmap.setPixel(20, 30, Color.RED); //这种修改无效 29 // 将获取的图片显示在ivSrc控件中 30 ivSrc.setImageBitmap(srcBitmap); 31 32 // 新建一个线程,在线程中对图片进行旋转 33 new Thread() { 34 int degrees = 0; 35 public void run() { 36 while(true){ 37 degrees += 5; 38 //每次旋转图片都要重新复制原图,重新设置画笔等,否则旋转后就是在复制后的图片上进行修改 39 // 复制原图片 40 final Bitmap copybitmap = Bitmap.createBitmap(srcBitmap.getWidth(), 41 srcBitmap.getHeight(), srcBitmap.getConfig()); 42 // 用canvas创建一个货补,以copybitmap为模板 43 final Canvas canvas = new Canvas(copybitmap); 44 // 创建一个画笔 45 final Paint paint = new Paint(); 46 // 创建一个矩阵对象 47 final Matrix matrix = new Matrix(); 48 49 //对图片进行旋转 50 matrix.setRotate(degrees, srcBitmap.getWidth()/2, srcBitmap.getHeight()/2); 51 canvas.drawBitmap(srcBitmap,matrix, paint); 52 //☆ 注意不能在子线程中直接更新activity页面ui 53 runOnUiThread(new Runnable() { 54 public void run() { 55 //将修改后的图片放入到相关ivRatate控件中 56 ivRatate.setImageBitmap(copybitmap); 57 } 58 }); 59 //让线程睡眠一秒钟,后继续执行 60 SystemClock.sleep(1000); 61 } 62 } 63 }.start(); 67 } 68 }
显示效果
时间: 2024-11-07 21:53:03