如何在科特林中心设置位图
How to set bitmap in center in kotlin
我如何将位图图像设置在中心而不是中心。这是我的代码,screen.I 尝试了很多但我没能解决这个问题
fun onDraw(c: Canvas, rectF: RectF, pos: Int) {
val p = Paint()
p.color = color
c.drawRect(rectF, p)
p.color = Color.WHITE
p.textSize - textSize.toFloat()
var r = Rect()
val cHeight = rectF.height()
val cWidth = rectF.width()
p.textAlign = Paint.Align.RIGHT
p.getTextBounds(text, 0, text.length, r)
var x = 0f
var y = 0f
if (imageResId == 0) {
x = cWidth / 2f - r.width() / 2f - r.left.toFloat()
y = cHeight / 2f + r.height() / 2f - r.bottom.toFloat()
c.drawText(text, rectF.left + x, rectF.top + y, p)
} else {
val d = ContextCompat.getDrawable(context, imageResId)
val bitmap = drawableToBitmap(d!!)
c.drawBitmap(
bitmap,
(rectF.left + rectF.right) / 2,
(rectF.top + rectF.bottom) / 2,
p
)
}
clickRegion = rectF
this.pos = pos
}
这是产生错误的图像 link
enter link description here
private fun drawableToBitmap(d: Drawable?): Bitmap {
if (d is BitmapDrawable) return d.bitmap
val bitmap =
Bitmap.createBitmap(d!!.intrinsicWidth, d.intrinsicHeight, Bitmap.Config.ARGB_8888)
var canvas = Canvas(bitmap)
d.setBounds(0, 0, canvas.width, canvas.height)
d.draw(canvas)
return bitmap
}
你可以看到你的可绘制对象都在中心并从那里绘制,你所做的一切都是正确的,你只需要一个简单的偏移量:
从中减去一半可绘制对象的宽度和高度 ]start position
红色到绿色
代码段
c.drawBitmap(
bitmap,
(rectF.left + rectF.right) / 2,
(rectF.top + rectF.bottom) / 2,
p
)
到
c.drawBitmap(
bitmap,
(rectF.left + rectF.right - bitmap.width) / 2,
(rectF.top + rectF.bottom - bitmap.height) / 2,
p
)
我如何将位图图像设置在中心而不是中心。这是我的代码,screen.I 尝试了很多但我没能解决这个问题
fun onDraw(c: Canvas, rectF: RectF, pos: Int) {
val p = Paint()
p.color = color
c.drawRect(rectF, p)
p.color = Color.WHITE
p.textSize - textSize.toFloat()
var r = Rect()
val cHeight = rectF.height()
val cWidth = rectF.width()
p.textAlign = Paint.Align.RIGHT
p.getTextBounds(text, 0, text.length, r)
var x = 0f
var y = 0f
if (imageResId == 0) {
x = cWidth / 2f - r.width() / 2f - r.left.toFloat()
y = cHeight / 2f + r.height() / 2f - r.bottom.toFloat()
c.drawText(text, rectF.left + x, rectF.top + y, p)
} else {
val d = ContextCompat.getDrawable(context, imageResId)
val bitmap = drawableToBitmap(d!!)
c.drawBitmap(
bitmap,
(rectF.left + rectF.right) / 2,
(rectF.top + rectF.bottom) / 2,
p
)
}
clickRegion = rectF
this.pos = pos
}
这是产生错误的图像 link enter link description here
private fun drawableToBitmap(d: Drawable?): Bitmap {
if (d is BitmapDrawable) return d.bitmap
val bitmap =
Bitmap.createBitmap(d!!.intrinsicWidth, d.intrinsicHeight, Bitmap.Config.ARGB_8888)
var canvas = Canvas(bitmap)
d.setBounds(0, 0, canvas.width, canvas.height)
d.draw(canvas)
return bitmap
}
你可以看到你的可绘制对象都在中心并从那里绘制,你所做的一切都是正确的,你只需要一个简单的偏移量:
从中减去一半可绘制对象的宽度和高度 ]start position
红色到绿色
代码段
c.drawBitmap(
bitmap,
(rectF.left + rectF.right) / 2,
(rectF.top + rectF.bottom) / 2,
p
)
到
c.drawBitmap(
bitmap,
(rectF.left + rectF.right - bitmap.width) / 2,
(rectF.top + rectF.bottom - bitmap.height) / 2,
p
)