Idioma

TextShaper Classe

Definição

Fornece formatação de texto para texto com vários estilos.

[Android.Runtime.Register("android/text/TextShaper", ApiSince=31, DoNotGenerateAcw=true)]
public class TextShaper : Java.Lang.Object
[<Android.Runtime.Register("android/text/TextShaper", ApiSince=31, DoNotGenerateAcw=true)>]
type TextShaper = class
    inherit Object
Herança
TextShaper
Atributos

Comentários

Fornece formatação de texto para texto com vários estilos.

Aqui está um exemplo de animação de tamanho de texto e espaçamento de letras para texto simples.

<code>
            // In this example, shape the text once for start and end state, then animate between two shape
            // result without re-shaping in each frame.
            class SimpleAnimationView @JvmOverloads constructor(
                    context: Context,
                    attrs: AttributeSet? = null,
                    defStyleAttr: Int = 0
            ) : View(context, attrs, defStyleAttr) {
                private val textDir = TextDirectionHeuristics.LOCALE
                private val text = "Hello, World."  // The text to be displayed

                // Class for keeping drawing parameters.
                data class DrawStyle(val textSize: Float, val alpha: Int)

                // The start and end text shaping result. This class will animate between these two.
                private val start = mutableListOf<Pair<PositionedGlyphs, DrawStyle>>()
                private val end = mutableListOf<Pair<PositionedGlyphs, DrawStyle>>()

                init {
                    val startPaint = TextPaint().apply {
                        alpha = 0 // Alpha only affect text drawing but not text shaping
                        textSize = 36f // TextSize affect both text shaping and drawing.
                        letterSpacing = 0f // Letter spacing only affect text shaping but not drawing.
                    }

                    val endPaint = TextPaint().apply {
                        alpha = 255
                        textSize =128f
                        letterSpacing = 0.1f
                    }

                    TextShaper.shapeText(text, 0, text.length, textDir, startPaint) { _, _, glyphs, paint ->
                        start.add(Pair(glyphs, DrawStyle(paint.textSize, paint.alpha)))
                    }
                    TextShaper.shapeText(text, 0, text.length, textDir, endPaint) { _, _, glyphs, paint ->
                        end.add(Pair(glyphs, DrawStyle(paint.textSize, paint.alpha)))
                    }
                }

                override fun onDraw(canvas: Canvas) {
                    super.onDraw(canvas)

                    // Set the baseline to the vertical center of the view.
                    canvas.translate(0f, height / 2f)

                    // Assume the number of PositionedGlyphs are the same. If different, you may want to
                    // animate in a different way, e.g. cross fading.
                    start.zip(end) { (startGlyphs, startDrawStyle), (endGlyphs, endDrawStyle) ->
                        // Tween the style and set to paint.
                        paint.textSize = lerp(startDrawStyle.textSize, endDrawStyle.textSize, progress)
                        paint.alpha = lerp(startDrawStyle.alpha, endDrawStyle.alpha, progress)

                        // Assume the number of glyphs are the same. If different, you may want to animate in
                        // a different way, e.g. cross fading.
                        require(startGlyphs.glyphCount() == endGlyphs.glyphCount())

                        if (startGlyphs.glyphCount() == 0) return@zip

                        var curFont = startGlyphs.getFont(0)
                        var drawStart = 0
                        for (i in 1 until startGlyphs.glyphCount()) {
                            // Assume the pair of Glyph ID and font is the same. If different, you may want
                            // to animate in a different way, e.g. cross fading.
                            require(startGlyphs.getGlyphId(i) == endGlyphs.getGlyphId(i))
                            require(startGlyphs.getFont(i) === endGlyphs.getFont(i))

                            val font = startGlyphs.getFont(i)
                            if (curFont != font) {
                                drawGlyphs(canvas, startGlyphs, endGlyphs, drawStart, i, curFont, paint)
                                curFont = font
                                drawStart = i
                            }
                        }
                        if (drawStart != startGlyphs.glyphCount() - 1) {
                            drawGlyphs(canvas, startGlyphs, endGlyphs, drawStart, startGlyphs.glyphCount(),
                                    curFont, paint)
                        }
                    }
                }

                // Draws Glyphs for the same font run.
                private fun drawGlyphs(canvas: Canvas, startGlyph: PositionedGlyphs,
                                       endGlyph: PositionedGlyphs, start: Int, end: Int, font: Font,
                                       paint: Paint) {
                    var cacheIndex = 0
                    for (i in start until end) {
                        intArrayCache[cacheIndex] = startGlyph.getGlyphId(i)
                        // The glyph positions are different from start to end since they are shaped
                        // with different letter spacing. Use linear interpolation for positions
                        // during animation.
                        floatArrayCache[cacheIndex * 2] =
                                lerp(startGlyph.getGlyphX(i), endGlyph.getGlyphX(i), progress)
                        floatArrayCache[cacheIndex * 2 + 1] =
                                lerp(startGlyph.getGlyphY(i), endGlyph.getGlyphY(i), progress)
                        if (cacheIndex == CACHE_SIZE) {  // Cached int array is full. Flashing.
                            canvas.drawGlyphs(
                                    intArrayCache, 0, // glyphID array and its starting offset
                                    floatArrayCache, 0, // position array and its starting offset
                                    cacheIndex, // glyph count
                                    font,
                                    paint
                            )
                            cacheIndex = 0
                        }
                        cacheIndex++
                    }
                    if (cacheIndex != 0) {
                        canvas.drawGlyphs(
                                intArrayCache, 0, // glyphID array and its starting offset
                                floatArrayCache, 0, // position array and its starting offset
                                cacheIndex, // glyph count
                                font,
                                paint
                        )
                    }
                }

                // Linear Interpolator
                private fun lerp(start: Float, end: Float, t: Float) = start * (1f - t) + end * t
                private fun lerp(start: Int, end: Int, t: Float) = (start * (1f - t) + end * t).toInt()

                // The animation progress.
                var progress: Float = 0f
                    set(value) {
                        field = value
                        invalidate()
                    }

                // working copy of paint.
                private val paint = Paint()

                // Array cache for reducing allocation during drawing.
                private var intArrayCache = IntArray(CACHE_SIZE)
                private var floatArrayCache = FloatArray(CACHE_SIZE * 2)
            }
</code>

Java documentação para android.text.TextShaper.

Partes desta página são modificações baseadas no trabalho criado e compartilhado pelo Project Open Source do Open Source e usadas de acordo com os termos descritos na Creative Commons 2.5.

Construtores

Nome Descrição
TextShaper(IntPtr, JniHandleOwnership)

Cria uma instância gerenciada que representa um objeto Java existente.

Propriedades

Nome Descrição
Class

Retorna a classe de runtime deste Object.

(Herdado de Object)
Handle

O identificador para a instância subjacente do Android.

(Herdado de Object)
JniIdentityHashCode

Obtém o código de hash de identidade atribuído a esse par Java pelo runtime de interoperabilidade.

(Herdado de Object)
JniManagedPeerState

Obtém os sinalizadores de estado atribuídos pela última vez pelo runtime.

(Herdado de JavaObject)
JniPeerMembers

Obtém os metadados JNI usados para acessar membros dessa associação Java.

PeerReference

Obtém a referência de objeto JNI para este par Java.

(Herdado de Object)
ThresholdClass

Obtém a classe Java usada para expedição de método virtual.

ThresholdType

Obtém o tipo gerenciado que declara essa associação de Java.

Métodos

Nome Descrição
Clone()

Cria e retorna uma cópia desse objeto.

(Herdado de Object)
Construct(JniObjectReference, JniObjectReferenceOptions)

Delega a construção desse par ao gerenciador de valores do runtime.

(Herdado de JavaObject)
Dispose()

Libera os recursos mantidos por esse par Java.

(Herdado de Object)
Dispose(Boolean)

Fornece um gancho de eliminação para subclasses. Essa implementação não executa nenhuma ação.

(Herdado de Object)
DisposeUnlessReferenced()

Pede ao gerenciador de valores para descartar esse par, a menos que seu mapeamento mantenha essa mesma instância gerenciada.

(Herdado de JavaObject)
Equals(Object)

Testa se outro par gerenciado se refere ao mesmo objeto Java.

(Herdado de JavaObject)
Equals(Object)

Indica se algum outro objeto é "igual a" este.

(Herdado de Object)
GetHashCode()

Retorna um valor de código hash para o objeto.

(Herdado de Object)
JavaFinalize()
Obsoleto.

Chamado pelo coletor de lixo em um objeto quando a coleta de lixo determina que não há mais referências ao objeto.

(Herdado de Object)
Notify()

Ativa um único thread que está aguardando no monitor deste objeto.

(Herdado de Object)
NotifyAll()

Ativa todos os threads que estão aguardando no monitor deste objeto.

(Herdado de Object)
SetHandle(IntPtr, JniHandleOwnership)

Define a propriedade Handle

(Herdado de Object)
SetPeerReference(JniObjectReference, JniObjectReferenceOptions)

Armazena um valor de referência no bloco de controle sem criar uma cópia de referência JNI.

(Herdado de JavaObject)
ShapeText(ICharSequence, Int32, Int32, ITextDirectionHeuristic, TextPaint, TextShaper+IGlyphsConsumer)

Formatar texto com vários estilos.

ShapeText(String, Int32, Int32, ITextDirectionHeuristic, TextPaint, TextShaper+IGlyphsConsumer)

Formatar texto com vários estilos.

ToArray<T>()

Cria uma matriz gerenciada com base nesse wrapper de matriz Java.

(Herdado de Object)
ToString()

Retorna uma representação de cadeia de caracteres do objeto.

(Herdado de Object)
UnregisterFromRuntime()

Cancela o registro desse par Java do runtime de interoperabilidade.

(Herdado de Object)
Wait()

Faz com que o thread atual aguarde até que ele seja despertado, normalmente por ser notificado ou interrompido.

(Herdado de Object)
Wait(Int64, Int32)

Faz com que o thread atual aguarde até que ele seja despertado, normalmente por ser notificado ou interrompido, ou até que uma determinada quantidade de tempo real tenha decorrido.

(Herdado de Object)
Wait(Int64)

Faz com que o thread atual aguarde até que ele seja despertado, normalmente por ser notificado ou interrompido, ou até que uma determinada quantidade de tempo real tenha decorrido.

(Herdado de Object)

Implantações explícitas de interface

Nome Descrição
IJavaPeerable.Disposed()

Marca esse par como descartado e chama Dispose com disposing set to true.

(Herdado de JavaObject)
IJavaPeerable.Finalized()

Marca esse par como descartado e chama Dispose com disposing set to false.

(Herdado de JavaObject)
IJavaPeerable.JniObjectReferenceControlBlock

Obtém o ponteiro de bloco de controle nativo usado por esse par.

(Herdado de JavaObject)
IJavaPeerable.SetJniIdentityHashCode(Int32)

Armazena o código de hash de identidade fornecido pelo runtime.

(Herdado de JavaObject)
IJavaPeerable.SetJniManagedPeerState(JniManagedPeerStates)

Substitui os sinalizadores de estado de par gerenciado armazenados.

(Herdado de JavaObject)
IJavaPeerable.SetPeerReference(JniObjectReference)

Atualiza a referência de par e libera o bloco de controle de um par descartado quando a referência é inválida.

(Herdado de JavaObject)

Métodos de Extensão

Nome Descrição
GetJniTypeName(IJavaPeerable)

Obtém o nome JNI do tipo da instância self.

JavaAs<TResult>(IJavaPeerable)

Tente coagir a digitar selfTResult, verificando se a coerção é válida no lado Java.

JavaCast<TResult>(IJavaObject)

Executa uma conversão de tipo marcada por runtime do Android.

JavaCast<TResult>(IJavaObject)

Reutiliza um par gerenciado compatível ou obtém um wrapper do tipo solicitado.

TryJavaCast<TResult>(IJavaPeerable, TResult)

Tente coagir a digitar selfTResult, verificando se a coerção é válida no lado Java.

Aplica-se a