当前位置:   article > 正文

超级简单的Android控件View转图片Bitmap_view needs to be laid out before calling drawtobit

view needs to be laid out before calling drawtobitmap()

直接上代码:

  1. fun getBitmapFromView(view: View): Bitmap {
  2. val bitmap = Bitmap.createBitmap(
  3. view.width, view.height,
  4. Bitmap.Config.ARGB_8888
  5. )
  6. val canvas = Canvas(bitmap)
  7. view.layout(0, 0, view.width, view.height)
  8. Log.d("ss", "combineImages: width: " + view.width)
  9. Log.d("ss", "combineImages: height: " + view.height)
  10. view.draw(canvas)
  11. view.requestLayout()
  12. return bitmap
  13. }

今天看了一下kotlin的源码,发现我根本就是多余的,哈哈,人家本来就已经有这种方法了,直接用就可以了

  1. /**
  2. * Return a [Bitmap] representation of this [View].
  3. *
  4. * The resulting bitmap will be the same width and height as this view's current layout
  5. * dimensions. This does not take into account any transformations such as scale or translation.
  6. *
  7. * Note, this will use the software rendering pipeline to draw the view to the bitmap. This may
  8. * result with different drawing to what is rendered on a hardware accelerated canvas (such as
  9. * the device screen).
  10. *
  11. * If this view has not been laid out this method will throw a [IllegalStateException].
  12. *
  13. * @param config Bitmap config of the desired bitmap. Defaults to [Bitmap.Config.ARGB_8888].
  14. */
  15. fun View.drawToBitmap(config: Bitmap.Config = Bitmap.Config.ARGB_8888): Bitmap {
  16. if (!ViewCompat.isLaidOut(this)) {
  17. throw IllegalStateException("View needs to be laid out before calling drawToBitmap()")
  18. }
  19. return Bitmap.createBitmap(width, height, config).applyCanvas {
  20. translate(-scrollX.toFloat(), -scrollY.toFloat())
  21. draw(this)
  22. }
  23. }

直接引用就可以

  1. override fun onCreate(savedInstanceState: Bundle?) {
  2. super.onCreate(savedInstanceState)
  3. setContentView(R.layout.activity_test)
  4. //textView.setpadding(10)
  5. textView.drawToBitmap(Bitmap.Config.ARGB_8888)
  6. }

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/261967
推荐阅读
相关标签
  

闽ICP备14008679号