activity:
package com.manss.myapplication
import android.annotation.SuppressLint
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.View.OnTouchListener
import android.widget.RelativeLayout
import androidx.appcompat.app.AppCompatActivity
class RotateActivity : AppCompatActivity(), OnTouchListener {
private var mRoot: RelativeLayout? = null
private var mCircle: RelativeLayout? = null
var i = 0
var viewRotation = 0f
var fingerRotation = 0.0
var newFingerRotation = 0.0
private var mImage: View? = null
@SuppressLint("ClickableViewAccessibility")
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_rotate_image)
mRoot = findViewById(R.id.root)
mCircle = findViewById(R.id.circle)
mImage = findViewById(R.id.rotate_image_image)
mRoot?.setOnTouchListener(this)
val mIndex = intArrayOf(0)
}
override fun onTouch(v: View, event: MotionEvent): Boolean {
val x = event.x
val y = event.y
//以控件中心为旋转中心
val xc = mRoot!!.width / 2.toFloat()
val yc = mRoot!!.height / 2.toFloat()
when (event.action) {
MotionEvent.ACTION_DOWN -> {
viewRotation = mCircle!!.rotation //记录当前点击时的角度
fingerRotation = Math.toDegrees(
Math.atan2(
x - xc.toDouble(),
yc - y.toDouble()
)
)
}
MotionEvent.ACTION_MOVE -> {
newFingerRotation = Math.toDegrees(
Math.atan2(
x - xc.toDouble(),
yc - y.toDouble()
)
)
mCircle!!.rotation = (viewRotation + newFingerRotation - fingerRotation).toFloat()
}
MotionEvent.ACTION_UP -> {
newFingerRotation = 0.0
fingerRotation = newFingerRotation
}
}
return true
}
}
activity_rotate_image.xml文件
android:rotationX="25"
表示绕X轴旋转25度,达到倾斜效果
作者:SmallWalnutBG