android之ImageView

先说两个过时的方法setBackgroundDrawablecontext.getResources().getDrawable(int resId)

第一个替代方法是setBackground和setImageDrawable。

第二个替代方法是ContextCompat.getDrawable(context, drawableID)。

ImageView可以在xml和代码里设置ScaleType的类型。

1.ImageVIew缩放。

这里先用到一个LinearLayout.LayoutParams类。官方介绍的是用来处理LinearLayout子布局的信息。用这个类来设置ImageView的宽高。

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(int Width, int Height);

然后在调用imageView.setLayoutParams(layoutParams);即可设置ImageView的宽高。

注意:这里的宽高最好不要超过屏幕的尺度。这里可以如下设置。

DisplayMetrics类是用来描述信息,大小,字体等信息的类。这里需要用到。

DisplayMetrics displayMetrics = new DisplayMetrics();

然后初始化displayMetrics对象,有点不一样。

activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);

displayMetrics.widthPixels和displayMetrics.heightPixels是屏幕像素的绝对宽度。ImageView的宽高不要大于这个值。

2.ImageView旋转。

//图片旋转,导入包要看好啊,android.graphics.Matrix
void rotateImage(ImageView imageView, int resId, int rotate) {
    Bitmap bitmap = ((BitmapDrawable) ContextCompat.getDrawable(context, resId)).getBitmap();
    Matrix matrix = new Matrix();
    matrix.setRotate(rotate);
    bitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
    imageView.setImageBitmap(bitmap);
}
这里先用bitmap加载drawable,方法BitmapDwawable.getBitmap()。然后是Matric类,必须使用reset(),setTranslate(),setRotate()其中一个方法来初始化。这里初始化成setRotate(),意指旋转类型,参数是旋转角度。然后再通过原先的bitmap和旋转矩阵构造一个新的bitmap。最后imageView.setImageBitmap(bitmap);即可产生旋转效果。



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值