const val TAG = "Yang"
class MainActivity : AppCompatActivity() {
var mRealView : MyImageView ?= null
var mRelativeLayout : MyRelativeLayout ?= null
var tempBitmap : Bitmap ?= null
var mHandler = Handler(Looper.getMainLooper())
var screenWidth = 0
var screenHeight = 0
var srcRect = RectF()
var destRect = RectF()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
mRealView = findViewById(R.id.real_iv)
mRelativeLayout = findViewById(R.id.real_rl)
screenWidth = resources.displayMetrics.widthPixels
screenHeight = resources.displayMetrics.heightPixels
val tempRect = RectF(0f, 0f, screenWidth.toFloat() / 2, screenHeight.toFloat() / 2)
CoroutineScope(Dispatchers.IO).launch {
tempBitmap = getBitmap(resources, tempRect, R.drawable.fake)
withContext(Dispatchers.Main) {
mRelativeLayout?.post {
srcRect.set(
0f,
0f,
mRelativeLayout?.width?.toFloat()!!,
mRelativeLayout?.height?.toFloat()!!
)
mRelativeLayout?.forEach { childView ->
if (childView is MyImageView) {
destRect.set(
0f,
0f,
childView.width.toFloat(),
childView.height.toFloat()
)
}
}
scaleRectFun(tempBitmap, srcRect, destRect)
}
}
}
}
fun scaleRectFun(tempBitmap: Bitmap?, srcRect : RectF, destRect: RectF){
tempBitmap?.let { bitmap->
mRelativeLayout?.setBitmap(bitmap)
val animator = ValueAnimator.ofFloat(0f, 1f)
animator.duration = 5000L
animator.interpolator = DecelerateInterpolator()
animator.addUpdateListener {
val value = it.animatedValue as Float
mRelativeLayout?.setDestRectCenterWithTranslate(srcRect, destRect, value)
}
animator.start()
}
}
}
fun getBitmap(resources : Resources, destRect : RectF, imageId: Int): Bitmap? {
var imageWidth = -1
var imageHeight = -1
val preOption = BitmapFactory.Options().apply {
inJustDecodeBounds = true
BitmapFactory.decodeResource(resources, imageId, this)
}
imageWidth = preOption.outWidth
imageHeight = preOption.outHeight
val scaleMatrix = Matrix()
var srcRect = RectF(0f, 0f, imageWidth.toFloat(), imageHeight.toFloat())
scaleMatrix.setRectToRect(srcRect, destRect, Matrix.ScaleToFit.CENTER)
scaleMatrix.mapRect(srcRect)
val finalOption = BitmapFactory.Options().apply {
if (imageHeight > 0 && imageWidth > 0) {
inPreferredConfig = Bitmap.Config.RGB_565
inSampleSize = calculateInSampleSize(
imageWidth,
imageHeight,
srcRect.width().toInt(),
srcRect.height().toInt()
)
}
}
return BitmapFactory.decodeResource(resources, imageId, finalOption)
}
fun calculateInSampleSize(fromWidth: Int, fromHeight: Int, toWidth: Int, toHeight: Int): Int {
var bitmapWidth = fromWidth
var bitmapHeight = fromHeight
if (fromWidth > toWidth|| fromHeight > toHeight) {
var inSampleSize = 2
while (bitmapWidth >= toWidth && bitmapHeight >= toHeight) {
bitmapWidth /= 2
bitmapHeight /= 2
inSampleSize *= 2
}
return inSampleSize
}
return 1
}