gpt4 book ai didi

android - 在布局之上绘制自定义 View

转载 作者:行者123 更新时间:2023-11-29 23:41:45 24 4
gpt4 key购买 nike

我想在屏幕上绘制一个自定义 View ,一个圆圈并对其进行操作。但是我想遵循面向对象的范例;能够添加更多圈子并让它们也与用户和布局进行交互。基本上,我希望 activity_main 成为“ Canvas ”并让圆圈移动并与布局交互。我是 android 图形的新手,所以我可以使用一些帮助和指导。这是我的代码:

主要 Activity :

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)
}
}

最佳答案

首先:获取对根布局的引用,例如

R.layout.activity_main 就像

<.... ConstraintLayout
android:id="+@id/container"
...>

setContentView 之后的 Activity 中

val container : ConstraintLayout = findViewById(R.id.container)

第二:要么使用你的默认 View 对象

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)

或者只是添加你可以在未来创建一个 Canvas 并像这样添加它

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()

关于android - 在布局之上绘制自定义 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51777766/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com