Android 图片的缩放与旋转

本文实现Android中的图片的缩放效果

首先设计布局:

<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:orientation="vertical"
    tools:context=".MainActivity" >

    <ImageView
        android:id="@+id/iv_1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

    <ImageView
        android:id="@+id/iv_2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
         />

</LinearLayout>

逻辑代码如下:

public class MainActivity extends Activity {

    private ImageView iv1;
    private ImageView iv2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        iv1 = (ImageView) findViewById(R.id.iv_1);
        iv2 = (ImageView) findViewById(R.id.iv_2);

        // 设置第一个bitmap的图标
        Bitmap bitmap1 = BitmapFactory.decodeResource(getResources(),
                R.drawable.ic_launcher);

        iv1.setImageBitmap(bitmap1);

        // 新建一个bitmap
        Bitmap alterBitmap = Bitmap.createBitmap(bitmap1.getWidth(),
                bitmap1.getHeight(), bitmap1.getConfig());

        // 以alterBitmap为模板新建画布
        Canvas canvas = new Canvas(alterBitmap);
        // 新建画笔并设置属性
        Paint paint = new Paint();
        paint.setColor(Color.BLACK);
        
        //新建矩阵并设置缩放值
        Matrix matrix = new Matrix();
        matrix.setValues(new float[] { 
                0.5f, 0, 0, 
                0, 1, 0, 
                0, 0, 1 
        });
        //设置画布
        canvas.drawBitmap(bitmap1, matrix, paint);
        iv2.setImageBitmap(alterBitmap);
    }

}

如果你对矩阵的设置不清楚,还可以使用下列api提供的方法替换上面标记部分的代码:

 matrix.setScale(0.5f, 1);

最后运行项目效果如下:

除了图像的缩放,还可以使图片旋转指定的角度,例如旋转180度

matrix.setRotate(180, bitmap1.getWidth() / 2, bitmap1.getHeight() / 2);

posted @ 2016-09-06 14:21  wuyudong  阅读(347)  评论(0编辑  收藏  举报
Top_arrow