我有两个正在苦苦挣扎的问题。首先是访问构造函数参数imagePath
(下面的代码),该参数在初始化程序块中无法访问:(我是Kotlin入门者)
class CustomView @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : View(context, attrs, defStyleAttr){
constructor(**imagePath:String**, context: Context) : this(context)
val paint = Paint()
val rectF = RectF()
val mPath = Path()
val drawable_bitmap: Drawable
var startX = 0f
var startY = 0f
var endX = 0f
var endY = 0f
val TAG = "CustomShapes"
init{
paint.color = Color.BLUE
paint.style = Paint.Style.STROKE
paint.flags = Paint.ANTI_ALIAS_FLAG
paint.strokeWidth = 10f
drawable_bitmap = loadBitmapDrawable(**imagePath**) //error here
}
private fun loadBitmapDrawable(imagePath: String): Drawable {
return resources.getDrawable(R.drawable.img,null)
}
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
if (((startY - endY)!=startY)|| (startX - endX)!=startX){
endY = endY.absoluteValue
endX = endX.absoluteValue
rectF.top = if (endY<startY)endY else startY
rectF.left = if (endX<startX) endX else startX
rectF.bottom = if (endY>startY)endY else startY
rectF.right = if (endX>startX) endX else startX
}
if (canvas!=null) {
drawable_bitmap.setBounds(canvas.clipBounds)
drawable_bitmap.draw(canvas)
}
// canvas?.drawRect(rectF,paint)
canvas?.drawOval(rectF,paint)
}
override fun onTouchEvent(event: MotionEvent?): Boolean {
if (event?.action == MotionEvent.ACTION_DOWN){
Log.d(TAG,"IN ACTION DOWN")
startX = event.x
startY = event.y
endX = startX
endY = startY
invalidate()
} else if (event?.action == MotionEvent.ACTION_MOVE){
Log.d(TAG,"ACTION MOVE")
endX = event.x
endY = event.y
invalidate()
}else if (event?.action == MotionEvent.ACTION_UP || event?.action == MotionEvent.ACTION_POINTER_UP ){
Log.d(TAG,"ACTION UP")
endX = event.x
endY = event.y
invalidate()
}
return true
}
}
其次,我拥有的代码当前填满了我的画布(附有屏幕截图),这也意味着我的图像被拉伸了。
我希望我的图像适合inside
的画布而不会拉伸或/并且在图像顶部将画布的大小与我的图像大小相同(无拉伸),以便可以在其上绘制一些形状。