【安卓UI】ImageView图片缩放与旋转实现整理

1、图片缩放

按照原图片宽高比缩放图片宽高即可。

  • 方法1:重新设置view宽高属性

//原图:width/height = 3/2
var newWidth = 300
var dw = newWidth
var dh = newWidth*2/3
zoomRotateImage.layoutParams = LinearLayout.LayoutParams(dw,dh)
  • 方法2:重新渲染位图

// 获得图片的宽高
var width = bm.getWidth()
var height = bm.getHeight()
// 计算缩放比例
var scaleWidth = (newWidth as Float) / width
var scaleHeight = (newHeight as Float) / height
// 取得想要缩放的matrix参数
var matrix =Matrix()
matrix.postScale(scaleWidth, scaleHeight)
// 得到新的图片
Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true)
zoomRotateImage.setImageBitmap(newbm)

2、图片旋转

  • 方法1:重新渲染位图

var bitmap = (resources.getDrawable(R.drawable.ic_launcher) as BitmapDrawable).getBitmap() 
var matrix  = Matrix()
matrix.setRotate(90)
var new = Bitmap.create(bitmap,0,bitmap.getWidth(),0,bitmap.getHeight(),matrix)  
imageView.setBitmapResource(bitmap) 
  • 方法2:设置ImageView旋转属性

可在xml中设置:


android:rotation="90"  

也可以在activity代码中写


image.setPivotX(image.getWidth()/2)  
image.setPivotY(image.getHeight()/2)  
image.setRotation(90)

//或者

var progress = 90 as Float
var matrix=Matrix()  
rotateImage.setScaleType(ScaleType.MATRIX)
matrix.postRotate(progress, pivotX, pivotY)  
rotateImage.setImageMatrix(matrix)
  • 方法3:使用旋转动画

//rotateImage.animate().rotation(90)

var rotateAnimation = RotateAnimation(lastAngle, progress, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 1)  
rotateAnimation.setFillAfter(true)
rotateAnimation.setDuration(50)
rotateAnimation.setRepeatCount(0)  
rotateImage.startAnimation(rotateAnimation)

参考资料:

1、老罗安卓开发-ImageView控件

2、Android UI之ImageView旋转的几种方式

3、Android 等比例缩放图片

4、android Matrix图片随意的放大缩小,拖动

5、图解 Android 动画中 android:pivotX 和 android:pivotY 属性的含义

6、LayoutParams 参数含义及转换dp

猜你喜欢

转载自blog.csdn.net/u012995888/article/details/80328109
今日推荐