Android - 使用 ImageView 时定义视图上的特定坐标 x 和 y 缩放类型 = "centerCrop"添加原始图像



a遇到问题,需要您的帮助!在我的应用程序中,需要根据原始位图图像(例如宽度:1230高度:2320(在特定位置绘制箭头(例如x=500,y=500(如果我使用scaleType="centerCrop"和imageView的特定宽度和高度,我如何计算imageView中的箭头位置?谢谢你的帮助!

class ArrowLayout : RelativeLayout {
lateinit var currentEmotion: EmotionEnums
private var xOffset: Float = 0f
private var yOffset: Float = 0f
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, att: AttributeSet?) : this(context, att, 0)
constructor(context: Context, att: AttributeSet?, def: Int) : super(context, att, def) {
initLayout()
}
private fun initLayout() {
View.inflate(context, R.layout.content_arrow_layout, this)
}
fun showImage(bitmap: Bitmap) {
findViewById<ImageView>(R.id.emotionImage).setImageBitmap(bitmap)
post {
xOffset =
if (bitmap.width >= this.width) -((bitmap.width - this.width) / 2).toFloat()
else ((this.width - bitmap.width) / 2).toFloat()
yOffset =
if (bitmap.height >= this.height) -((bitmap.height - this.height) / 2).toFloat()
else ((this.height - bitmap.height) / 2).toFloat()
drawArrows()
}
}
private fun drawArrows() {
addView(ImageView(context).apply {
layoutParams = LayoutParams(30, 55)
setImageResource(R.drawable.arrow_oblique_right_green)
x = 500 + xOffset
y = 600 + yOffset
requestLayout()
})
}
}

视图的xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/emotionImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="centerCrop"
tools:ignore="ContentDescription" />
</RelativeLayout>

居中裁剪意味着它将居中图像,然后裁剪外部。因此,如果图像是imgHeight x imgWidth,则视图是viewHeight x viewWidth,并且您要指向的像素位于图像中的x,y

如果imgHeight>viewHeight,则数学表达式为:

y-(imgHeight-viewHeight)/2

基本上是将y减少顶部裁剪的图片量(这是高度差的一半,另一半在底部裁剪(。如果此答案为负数或大于viewHeight,则箭头指向屏幕外(已裁剪(。

如果imgHeight<=viewHeight,数学为:

y+(viewHeight- imageHeight)/2

基本上将底部填充添加到视图高度。底部衬垫的高度应再次相差一半。

x方向是一样的,但有x和宽度。

最新更新