【问题标题】:How to handle screen orientation in Canvas of Android?如何在 Android 的 Canvas 中处理屏幕方向?
【发布时间】:2022-06-14 15:47:01
【问题描述】:

我在 Android 中使用 Canvas,我面临的问题是在屏幕旋转期间。假设我以纵向模式启动应用程序并在画布上绘制一些东西,然后在旋转时画布的某些部分移出屏幕。请参阅随附的屏幕截图。

我的文件中的代码 sn-ps 实现了 Canvas(如果需要,我将提供其他部分,请通过评论告诉我):

    private lateinit var mBitmap: Bitmap
    private lateinit var mCanvas: Canvas
override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        canvas.apply {
            drawColor(0)
            drawBitmap(mBitmap, 0f, 0f, mBitmapPaint)
            drawPath(mPath, mPaint)
        }
    }
    private fun createBitmap(w: Int, h: Int) {
        val bitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
        mBitmap = bitmap
        mCanvas = Canvas(bitmap)
        clear()
    }
 private fun createBitmap() {
        val p = displayDimensions
        val bitmapSize = max(p.x,p.y)
        createBitmap(bitmapSize, bitmapSize)
    }
init {
        mPaint = Paint()
        mPaint.isAntiAlias = true
        mPaint.isDither = true
        mPaint.color = foregroundColor
        mPaint.style = Paint.Style.STROKE
        mPaint.strokeJoin = Paint.Join.ROUND
        mPaint.strokeCap = Paint.Cap.ROUND
        mPaint.strokeWidth = currentStrokeWidth.toFloat()
        createBitmap()
}

【问题讨论】:

    标签: android kotlin canvas android-canvas screen-orientation


    【解决方案1】:

    浏览了几个博客和 SO 答案,我终于在 Android 开发者文档中找到了答案 - here

    我的代码 sn-p 看起来像:

    private var mBitmap: Bitmap? = null
    
    override fun onSizeChanged(w: Int, h: Int, oldw: Int, oldh: Int) {
            super.onSizeChanged(w, h, oldw, oldh)
            mBitmap = if (mBitmap == null) {
                Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)
            } else {
                val scaledBitmap: Bitmap = Bitmap.createScaledBitmap(mBitmap!!, w, h, true)
                scaledBitmap
            }
            mCanvas = Canvas(mBitmap!!)
        }
    

    这样您可以在设备旋转时处理屏幕方向。 createScaledBitmap() 函数负责处理先前绘制的位图并根据新的宽度和高度对其进行缩放。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-06-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多