使用Canvas绘制文本而不使用TextView对象

问题描述 投票:-1回答:1

我想创建一个自定义视图。该视图将具有使用画布绘制的文本。绘制的文本不使用任何TextView对象。

我试图使用画布绘制文本。这是我的代码:

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
    }
}
class CustomView(context: Context , attributeSet: AttributeSet) : View(context,attributeSet) {
    private val paint: Paint = Paint().apply {
        style = Paint.Style.FILL
        color = Color.WHITE
        textSize = 30f
        textAlign = Paint.Align.CENTER
        isAntiAlias = true
    }
    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        canvas!!.drawText("Custom View",0f,0f,paint)
    }
}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
    <com.shaheen.drawtext.CustomView
        android:layout_gravity="center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>

我尝试了此代码,但未在该视图中绘制文本。它显示一个空白屏幕。

android android-canvas android-custom-view drawtext
1个回答
0
投票

通过这样做,绘制了文本。在这里,我将油漆的颜色更改为Black color

private val paint: Paint = Paint().apply {
        style = Paint.Style.FILL_AND_STROKE
        color = Color.BLACK
        textSize = headingTextSize
        textAlign = Paint.Align.LEFT
        typeface = Typeface.create(Typeface.DEFAULT, Typeface.BOLD)
        isAntiAlias = true

}
© www.soinside.com 2019 - 2024. All rights reserved.