Как сохранить рисунок холста в базе данных Room (SQLITE) и получить его для возобновления редактирования - PullRequest
0 голосов
/ 22 апреля 2020

Я занимаюсь разработкой приложения Android, в котором у меня есть холст (рисунок свободной рукой и фигуры). И мне нужно сохранить холст в базе данных комнат, когда пользователь его сохраняет, и мне нужно извлечь холст, чтобы возобновить редактирование, где пользователь ушел. Итак, я искал и узнал, что мне нужно сохранить растровое изображение, но я не могу понять, как? Может ли кто-нибудь помочь мне сохранить мой рисунок? заранее спасибо! ниже мой класс DrawView:

class DrawView(context: Context, attrs: AttributeSet?) : View( context, attrs ) {


    var BRUSH_SIZE = 10f
    val DEFAULT_COLOR = Color.RED
    val DEFAULT_BG_COLOR = Color.WHITE
    private val TOUCH_TOLERANCE = 4f

    private var mX = 0f
    private  var mY: Float = 0f
    private var mPath: Path? = null
    private var mPaint: Paint? = null
    private var currentColor = 0
    private var defaultBgColor = DEFAULT_BG_COLOR
    private var strokeWidth = 0f
    private var mBitmap: Bitmap? = null
    private var mCanvas: Canvas? = null
    private val mBitmapPaint = Paint(Paint.DITHER_FLAG)

    private val paths: ArrayList<Draw> = ArrayList()
    private val undo: ArrayList<Draw> = ArrayList()

    init{
        mPaint = Paint()
        mPaint!!.isAntiAlias = true
        mPaint!!.isDither = true
        mPaint!!.color = DEFAULT_COLOR
        mPaint!!.style = Paint.Style.STROKE
        mPaint!!.strokeJoin = Paint.Join.ROUND
        mPaint!!.strokeCap = Paint.Cap.ROUND
        mPaint!!.xfermode = null
        mPaint!!.alpha = 0xff
    }

    fun initialise(displayMetrics: DisplayMetrics) {
        val height = displayMetrics.heightPixels
        val width = displayMetrics.widthPixels
        mBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
        mCanvas = Canvas(mBitmap!!)
        currentColor = DEFAULT_COLOR
        strokeWidth = BRUSH_SIZE
    }

    override fun onDraw(canvas: Canvas) {
        canvas.save()
        mCanvas!!.drawColor(defaultBgColor) // WRONG
        for (draw in paths) {
            mPaint!!.color = draw.color // WRONG
            mPaint!!.strokeWidth = draw.strokeWidth
            mPaint!!.maskFilter = null
            mCanvas!!.drawPath(draw.path, mPaint!!)
        }
        canvas.drawBitmap(mBitmap!!, 0f, 0f, mBitmapPaint)
        canvas.restore()
    }

    private fun touchStart(x: Float, y: Float) {
        mPath = Path()
        val draw = Draw(currentColor, strokeWidth, mPath!!)
        paths.add(draw)
        mPath!!.reset()
        mPath!!.moveTo(x, y)
        mX = x
        mY = y
    }

    private fun touchMove(x: Float, y: Float) {
        val dx = Math.abs(x - mX)
        val dy: Float = Math.abs(y - mY)
        if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
            mPath!!.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2)
            mX = x
            mY = y
        }
    }

    private fun touchUp() {
        mPath!!.lineTo(mX, mY)
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        val x = event.x
        val y = event.y
        when (event.action) {
            MotionEvent.ACTION_DOWN -> {
                touchStart(x, y)
                invalidate()
            }
            MotionEvent.ACTION_UP -> {
                touchUp()
                invalidate()
            }
            MotionEvent.ACTION_MOVE -> {
                touchMove(x, y)
                invalidate()
            }
        }
        return true
    }

    fun clear() {
        defaultBgColor = DEFAULT_BG_COLOR
        paths.clear()
        invalidate()
    }

    fun undo() {
        if (paths.size > 0) {
            undo.add(paths.removeAt(paths.size - 1))
            invalidate() // add
        } else {
            Toast.makeText(context, "Nothing to undo", Toast.LENGTH_LONG).show()
        }
    }

    fun redo() {
        if (undo.size > 0) {
            paths.add(undo.removeAt(undo.size - 1))
            invalidate() // add
        } else {
            Toast.makeText(context, "Nothing to undo", Toast.LENGTH_LONG).show()
        }
    }

    fun setStrokeWidth(width: Float) {
        strokeWidth = width
    }

    fun setColor(color: Int) {
        currentColor = color
    }

    fun saveImage() {
        var count = 0
        val sdDirectory: File = Environment.getExternalStorageDirectory()
        val subDirectory = File(sdDirectory.toString().toString() + "/Pictures/Paint")
        if (subDirectory.exists()) {
            val existing: Array<File> = subDirectory.listFiles()
            for (file in existing) {
                if (file.name.endsWith(".jpg") || file.name.endsWith(".png")) {
                    count++
                }
            }
        } else {
            subDirectory.mkdir()
        }
        if (subDirectory.exists()) {
            val image = File(subDirectory, "/drawing_" + (count + 1) + ".png")
            val fileOutputStream: FileOutputStream
            try {
                fileOutputStream = FileOutputStream(image)
                mBitmap!!.compress(Bitmap.CompressFormat.PNG, 100, fileOutputStream)
                fileOutputStream.flush()
                fileOutputStream.close()
                Toast.makeText(context, "saved", Toast.LENGTH_LONG).show()
            } catch (e: FileNotFoundException) {
            } catch (e: IOException) {
            }
        }
    }

    fun getPathList() = this.paths
}
...