MainActivity.kt
class MainActivity : AppCompatActivity() {
val binding by lazy {
ActivityMainBinding.inflate(layoutInflater)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(binding.root)
// 객체 생성
val customView = CustomView(this)
// frameLayout 에 customView 추가
binding.frameLayout.addView(customView)
}
}
class CustomView(context: Context) : View(context) {
override fun onDraw(canvas: Canvas?) {
super.onDraw(canvas)
// 객체 선언
val paint = Paint()
// 메서드 수정
paint.color = Color.BLACK
paint.textSize = 100f
// canvas에 직접 그리기
canvas?.drawText("존나 졸려 ㅁㅊ", 100f, 100f, paint)
val blue = Paint()
blue.color = Color.BLUE
blue.style = Paint.Style.FILL
canvas?.drawCircle(150f, 300f, 100f, blue)
val red = Paint()
red.color = Color.RED
red.style = Paint.Style.STROKE
canvas?.drawCircle(400f, 300f, 100f, red)
val green = Paint()
green.color = Color.GREEN
green.strokeWidth = 20f
green.style = Paint.Style.STROKE
val rect = Rect(50, 450, 250, 650)
canvas?.drawRect(rect, green)
val cyan = Paint()
cyan.color = Color.CYAN
cyan.style = Paint.Style.FILL
val rectF = RectF(300f, 450f, 500f, 650f)
canvas?.drawRoundRect(rectF, 30f, 30f, cyan)
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="44dp"
android:layout_marginBottom="1dp"
android:text="Draw Text"
app:layout_constraintBottom_toTopOf="@+id/frameLayout"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="1dp"
android:layout_marginEnd="1dp"
android:layout_marginBottom="1dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/textView">
</FrameLayout>
</androidx.constraintlayout.widget.ConstraintLayout>