Android 图片缩放实例详解

2019/7/7 21:23:44

本文主要是介绍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);

    注意:     新建矩阵并设置缩放值

       Matrix matrix = new Matrix();
        matrix.setValues(new float[] {
                0.5f, 0, 0,
                0, 1, 0,
                0, 0, 1
        });

最后运行项目效果如下:

以上就是对Android 图片缩放的资料整理,后续继续补充相关知识,谢谢大家对本站的支持!



这篇关于Android 图片缩放实例详解的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程