Android画布Canvas绘制手指MotionEvent.ACTION_MOVE 事件矩形方框,Kotlin

2023-12-26 23:34:39

Android画布Canvas绘制手指MotionEvent.ACTION_MOVE 事件矩形方框,Kotlin

?

?

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.graphics.Rect
import android.os.Bundle
import android.util.AttributeSet
import android.view.MotionEvent
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.AppCompatImageView


class MainActivity : AppCompatActivity() {
    private var image: MyImage? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        image = findViewById(R.id.image)
    }
}

class MyImage : AppCompatImageView {
    private var curX: Float? = 0f
    private var curY: Float? = 0f

    private var mIsDraw = false

    constructor(ctx: Context, attrs: AttributeSet) : super(ctx, attrs) {

    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        when (event?.actionMasked) {
            MotionEvent.ACTION_DOWN -> {
                mIsDraw = true
            }

            MotionEvent.ACTION_MOVE -> {
                curX = event?.x
                curY = event?.y

                invalidate()
            }

            MotionEvent.ACTION_UP -> {
                mIsDraw = false
            }
        }

        return true
    }

    override fun draw(canvas: Canvas) {
        super.draw(canvas)

        if (mIsDraw) {
            myDraw(canvas)
        }
    }

    private fun myDraw(canvas: Canvas) {
        val paint = Paint(Paint.ANTI_ALIAS_FLAG)
        paint.color = Color.RED
        paint.style = Paint.Style.STROKE
        paint.strokeWidth = 40f

        val w = 400
        val h = 300
        val rect = Rect((curX!! - w / 2).toInt(), (curY!! - h / 2).toInt(), (curX!! + w / 2).toInt(), (curY!! + h / 2).toInt())

        canvas.drawRect(rect, paint) //在这块区域边框绘制线。
    }
}

?

手指在屏幕上移动,红色方框跟随手指的位置移动,手指接触屏幕的位置为红色方框的中心:

efd94f64c28c417fbb69bdc92490af1e.png

?

?

?

Android画布Canvas绘制drawBitmap基于源Rect和目的Rect,Kotlin-CSDN博客文章浏览阅读1.3k次,点赞19次,收藏15次。文章浏览阅读9.6k次。文章浏览阅读1.8k次。/*Java代码 将Drawable转化为Bitmap */ Bitmap drawableToBitmap(Drawable drawable) { int width = drawable.getIntrinsicWidth();Android Material Design :LinearLayoutCompat添加分割线divider_linearlayout 分割线-CSDN博客。https://blog.csdn.net/zhangphil/article/details/134818221Android手势缩放图片以及图片黏贴在手指随手势移动_android 图片缩放跟随手指的例子-CSDN博客文章浏览阅读3.5k次。一个Android手势缩放图片的工具类;同时,此类还实现另外一个功能:当手指按在触屏上移动时候,图片“黏贴”在手指上随手指移动而整体移动。具体使用方法可以是这样:先new一个此类的实例,然后在ImageView的方法setOnTouchListener(new ImageViewOnMultiTouchListener());例如:ImageViewOnMultiTouchListen_android 图片缩放跟随手指的例子https://blog.csdn.net/zhangphil/article/details/43965701

?

文章来源:https://blog.csdn.net/zhangphil/article/details/135160784
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。