我想在屏幕上绘制一个自定义视图(一个圆圈)并对其进行操作。但是我想遵循面向对象的范式。能够添加更多的圈子,并使它们也与用户和布局互动。基本上,我希望activity_main是“画布”,并让圆移动并与布局交互。我是Android图形的新手,因此可以使用一些帮助和指导。这是我的代码:
MainActivity:
package com.example.canvasbounds
import android.app.Activity
import android.os.Bundle
class MainActivity : Activity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val circle= Circle(400f,600f, this)
circle.invalidate()
}
}
圆圈:
package com.example.canvasbounds
import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Paint
import android.view.View
class Circle(x: Float, y: Float, context: Context) : View(context) {
val paint = Paint().apply {
color = Color.BLUE
style = Paint.Style.STROKE
strokeWidth = 8f
}
override fun onDraw(canvas: Canvas?) {
canvas?.drawCircle(x,y,100f,paint)
}
}
答案 0 :(得分:1)
首先:获取对根布局的引用,例如
R.layout.activity_main就像
<.... ConstraintLayout
android:id="+@id/container"
...>
setContentView
之后的活动
val container : ConstraintLayout = findViewById(R.id.container)
第二:要么使用您的默认视图对象
setContentView(R.layout.activity_main)
val container : ConstraintLayout = findViewById(R.id.container)
val circle= Circle(400f,600f, this)
circle.invalidate()
circle.layoutpramas = LayoutParams(25, 25) // for placement on screen,
container.addView(circle)
或者只是添加您就可以在将来创建画布并像这样添加它
setContentView(R.layout.activity_main)
val container : ConstraintLayout = findViewById(R.id.container)
val circle= Circle(400f,600f, this)
circle.invalidate()
circle.layoutpramas = LayoutParams(25, 25) // for placement on screen, different for different layout
container.addView(circle)
val canvas = Canvas()
canvas.drawColor(Color.RED);
circle.draw(canvas)
circle.invalidate()