【安卓UI】ImageView圖片縮放與旋轉實現整理
阿新 • • 發佈:2019-01-28
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)
參考資料: