全屏图片适配

282 阅读1分钟
 DownloadManager.getInstance().downloadImage(data[0].pictureUrl, object : OnDownloadListener() {
                override fun onDownloadSuccess(filePath: String?) {
                    val screenWidth = this@LoadingActivity.resources.displayMetrics.widthPixels
                    val screenHeight = this@LoadingActivity.resources.displayMetrics.heightPixels

                    val bitmap = BitmapFactory.decodeFile(filePath)
                    val bitmapWith = bitmap.width
                    val bitmapHeight = bitmap.height
                    //此处获屏幕取宽高比
                    val screenRate = ((screenHeight.toFloat() / screenWidth.toFloat()) * 100) / 100
 
                    //此处获取图片宽高比       
            val bitmapRate = ((bitmapHeight.toFloat() / bitmapWith.toFloat()) * 100) / 100

   //图片宽高比大于屏幕宽高比的话肯定相对于屏幕来说,是个长图,此时以宽为基础,等比例缩放或者放大。
                    if (bitmapRate > screenRate) {
                         //算出屏幕和图片的宽度比例
                        val witdhRate = ((screenWidth.toFloat() / bitmapWith.toFloat()) * 100) / 100
                       //根据屏幕宽高比算出图片所需高度
                         val finalheight = (bitmapHeight * witdhRate).toInt()
                        //获得缩放或者放大的图片此时的图片高度肯定是大于屏幕高度的
                        var tempBimap = Bitmap.createScaledBitmap(bitmap, screenWidth, finalheight, true)
                       //接下来从顶部截取屏幕高度的图片bitmap,即为最终图片
                       var finalBitmap = Bitmap.createBitmap(tempBimap, 0, 0, screenWidth.toInt(), screenHeight.toInt())
                       //赋值到imageview中
                        siv_Daily_Message.setImageBitmap(finalBitmap)
                    } else if (bitmapRate < screenRate) {
 //图片宽高比小于屏幕宽高比的话肯定相对于屏幕来说,是个宽图,此时以高为基础,等比例缩放或者放大。
                        //此时高相对小,宽相对大,求出高的比例
                        val heightRate = ((screenHeight.toFloat() / bitmapHeight.toFloat()) * 100) / 100
                       求出图片需要的宽度
                         val finalwidth = (bitmapWith * heightRate).toInt()
                       //获得缩放或者放大的图片此时的图片宽度肯定是大于屏幕宽度的
                          var tempBimap = Bitmap.createScaledBitmap(bitmap, finalwidth, screenHeight, true)
                        var startx = (finalwidth - screenWidth) / 2
                       、、用屏幕的宽高,截取图片的中间,获取到最终图片
                          var finalBitmap = Bitmap.createBitmap(tempBimap, startx, 0, screenWidth.toInt(), screenHeight.toInt())
                        siv_Daily_Message.setImageBitmap(finalBitmap)
                    } else {
                      //同比例直接赋值imageview
                        siv_Daily_Message.setImageBitmap(bitmap)
                    }
                }

                override fun onDownloadFailed(e: Exception?) {
                    e?.printStackTrace()
                }
            })