Es el Año del Conejo, usemos Componer para dibujar conejos

Estoy participando en el concurso de contribución creativa "Rabbit, a Rabbit". Para obtener más información, consulte: Concurso de contribución creativa "Rabbit, a Rabbit" . Este año ha llegado el año del conejo. Recuerdo haber visto a muchos desarrolladores dibujar con Compose el año pasado. Tigre, hay todo tipo de tigres. Ahora que es el año del conejo, de repente quiero usar Compose para dibujar un conejo y probarlo. Por cierto, no he tocado Compose en mucho tiempo. .

Preparación

El conejo se dibuja principalmente en el lienzo, por lo que primero debemos generar un lienzo y luego determinar el ancho, la altura y el color del pincel del lienzo.

val drawColor = colorResource(id = R.color.color_EC4126)
Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) {

}
复制代码

El ancho y la altura son solo dos valores codificados. También podemos usar la API del sistema para obtener el ancho y la altura reales de la pantalla. El color del pincel es rojizo.

cabeza

La cabeza es en realidad una elipse. Usamos el método drawPath de canvas para dibujar. Lo que tenemos que hacer es determinar las coordenadas del punto central de la elipse, y las coordenadas superior izquierda e inferior derecha de la elipse.

val startX = screenWidth() / 4
val startY = screenHeight() / 3
val headPath = Path()
headPath.moveTo(screenWidth() / 2, screenHeight() / 2)
headPath.addOval(Rect(startX, startY, screenWidth() - startX, screenHeight() - startY))
headPath.close()
Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) {
    drawPath(path = headPath, color = drawColor, style = Stroke(width = 12f))
}

复制代码

Las coordenadas del eje x y del eje y del punto central de la cabeza son la mitad del ancho y la altura del lienzo, la coordenada x en la parte superior izquierda es un cuarto del ancho del lienzo, la coordenada y es un tercio del altura del lienzo, y la coordenada x en la parte inferior derecha es el ancho del lienzo Reste la coordenada x de la esquina superior izquierda, y la coordenada y de la esquina inferior derecha es para restar la coordenada y de la esquina superior izquierda, y finalmente dibuje la ruta de este elipse en el Lienzo, veamos el renderizado

tt1.png

oído

Después de dibujar la cabeza, dibujemos las orejas. Las dos orejas son en realidad dos elipses, que son simétricas con respecto a la línea central. La idea del dibujo es la misma que la de dibujar la cabeza. Determine las coordenadas de los puntos centrales de los dos caminos. , y las coordenadas xy de la parte superior izquierda e inferior derecha de cada

val leftEarPath = Path()
val leftEarPathX = screenWidth() * 3 / 8
val leftEarPathY = screenHeight() / 6
leftEarPath.moveTo(leftEarPathX, leftEarPathY)
leftEarPath.addOval(
    Rect(
        leftEarPathX - 60f,
        leftEarPathY / 2,
        leftEarPathX + 60f,
        startY + 30f
    )
)
leftEarPath.close()

val rightEarPath = Path()
val rightEarPathX = screenWidth() * 5 / 8
val rightEarPathY = screenHeight() / 6
rightEarPath.moveTo(rightEarPathX, rightEarPathY)
rightEarPath.addOval(
    Rect(
        rightEarPathX - 60f,
        rightEarPathY / 2,
        rightEarPathX + 60f,
        startY + 30f
    )
)
rightEarPath.close()
Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) {
    drawPath(path = leftEarPath, color = drawColor, style = Stroke(width = 10f))
    drawPath(path = rightEarPath, color = drawColor, style = Stroke(width = 10f))
}
复制代码

Mira las representaciones

tt2.png

oído interno

De esta manera, las orejas no son muy tridimensionales y se ven un poco planas, después de todo, las orejas de conejo se sentirán un poco hundidas, por lo que agregamos un oído interno a este par de orejas para aumentar el efecto tridimensional. El oído interno es realmente muy simple, y la razón es la misma que la del oído externo. Las coordenadas xy del punto central y el punto superior izquierdo y el punto inferior derecho serán más pequeños. Podemos cambiar la trayectoria del oído externo a un poquito.

val leftEarSubPath = Path()
val leftEarSubPathX = screenWidth() * 3 / 8
val leftEarSubPathY = screenHeight() / 4
leftEarSubPath.moveTo(leftEarSubPathX, leftEarSubPathY)
leftEarSubPath.addOval(
    Rect(
        leftEarSubPathX - 30f,
        screenHeight() / 6,
        leftEarSubPathX + 30f,
        startY + 30f
    )
)
leftEarSubPath.close()

val rightEarSubPath = Path()
val rightEarSubPathX = screenWidth() * 5 / 8
val rightEarSubPathY = screenHeight() / 4
rightEarSubPath.moveTo(rightEarSubPathX, rightEarSubPathY)
rightEarSubPath.addOval(
    Rect(
        rightEarSubPathX - 30f,
        screenHeight() / 6,
        rightEarSubPathX + 30f,
        startY + 30f
    )
)
rightEarSubPath.close()
Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) {
    drawPath(path = leftEarSubPath, color = drawColor, style = Stroke(width = 6f))
    drawPath(path = rightEarSubPath, color = drawColor, style = Stroke(width = 6f))
}
复制代码

Mira las representaciones

tt31.png

Hay un sabor interno, y el grosor del cepillo del oído interno se reduce ligeramente. Para resaltar lo casi grande, lo pequeño, jajaja, vayamos al siguiente paso.

Ojo

Después de dibujar las orejas, comenzamos a dibujar los ojos. Los ojos también son muy fáciles de dibujar. Lo principal es encontrar la posición del punto central. La coordenada x del punto central es en realidad la misma que la coordenada x de la oreja, y la coordenada y está ligeramente más cerca de la coordenada y del punto central de la cabeza.

val leftEyePath = Path()
val leftEyePathX = screenWidth() * 3 / 8
val leftEyePathY = screenHeight() * 11 / 24
leftEyePath.moveTo(leftEyePathX, leftEyePathY)
leftEyePath.addOval(
    Rect(
        leftEyePathX - 35f,
        leftEyePathY - 35f,
        leftEyePathX + 35f,
        leftEyePathY + 35f
    )
)
leftEyePath.close()

val rightEyePath = Path()
val rightEyePathX = screenWidth() * 5 / 8
val rightEyePathY = screenHeight() * 11 / 24
rightEyePath.moveTo(rightEyePathX, rightEyePathY)
rightEyePath.addOval(
    Rect(
        rightEyePathX - 35f,
        rightEyePathY - 35f,
        rightEyePathX + 35f,
        rightEyePathY + 35f
    )
)
rightEyePath.close()
Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) {
    drawPath(path = leftEyePath, color = drawColor, style = Stroke(width = 10f))
    drawPath(path = rightEyePath, color = drawColor, style = Stroke(width = 10f))
}

复制代码

Las representaciones son las siguientes

tt4.png

眼神有点空洞,无神是不,缺个眼珠子,那我们再给小兔子画上眼珠吧,眼珠就在眼睛的中心点位置,画一个圆点,圆点就要用到drawCircle,它有这些属性

fun drawCircle(
    color: Color,
    radius: Float = size.minDimension / 2.0f,
    center: Offset = this.center,
    /*@FloatRange(from = 0.0, to = 1.0)*/
    alpha: Float = 1.0f,
    style: DrawStyle = Fill,
    colorFilter: ColorFilter? = null,
    blendMode: BlendMode = DefaultBlendMode
)
复制代码

我们不需要用到全部,只需要用到颜色color,也就是红色,圆点半径radius,肯定要比眼睛的半径要小一点,我们就设置为10f,圆点中心坐标center,就是眼睛的中心点坐标,知道了以后我们开始绘制眼珠

Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) { 
    drawCircle(color = drawColor, radius = 10f, center = Offset(leftEyePathX,leftEyePathY))
    drawCircle(color = drawColor, radius = 10f, center = Offset(rightEyePathX,rightEyePathY))
}
复制代码

我们再看下效果图

imagen.png

鼻子

接下去我们画鼻子,鼻子肯定在脑袋的中间,所以中心点x坐标就是脑袋中心点的x坐标,那鼻子的y坐标就设置成比中心点y坐标稍微高一点的位置,代码如下

val nosePath = Path()
val nosePathX = screenWidth() / 2
val nosePathY = screenHeight() * 13 / 24
nosePath.moveTo(nosePathX, nosePathY)
nosePath.addOval(Rect(nosePathX - 15f, nosePathY - 15f, nosePathX + 15f, nosePathY + 15f))
nosePath.close()
Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) { 
    drawPath(path = nosePath, color = drawColor, style = Stroke(width = 10f))
}

复制代码

我们看下效果图

imagen.png

兔唇

兔子的样子逐渐出来了,画完鼻子我们接着画啥呢?没错,兔子最有特点的位置也就是兔唇,我们脑补下兔唇长啥样子,首先位置肯定是在鼻子的下面,然后从鼻子开始往两边分叉,也就是两个扇形,扇形怎么画呢,我们也有现成的api,drawArc,我们看下drawArc都提供了哪些属性

fun drawArc(
    color: Color,
    startAngle: Float,
    sweepAngle: Float,
    useCenter: Boolean,
    topLeft: Offset = Offset.Zero,
    size: Size = this.size.offsetSize(topLeft),
    /*@FloatRange(from = 0.0, to = 1.0)*/
    alpha: Float = 1.0f,
    style: DrawStyle = Fill,
    colorFilter: ColorFilter? = null,
    blendMode: BlendMode = DefaultBlendMode
)
复制代码

我们需要用到的就是颜色color,这个扇形起始角度startAngle,扇形终止的角度sweepAngle,是否扇形两端跟中心点连接起来的布尔值useCenter,扇形的左上位置topLeft以及扇形的大小size也就是设置半径,知道这些以后我们开始逐个代入参数吧

Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) { 
    drawArc(
        color = drawColor,
        0f,
        120f,
        style = Stroke(width = 10f),
        useCenter = false,
        size = Size(120f, 120f),
        topLeft = Offset(nosePathX - 120f, nosePathY)
    )

    drawArc(
        color = drawColor,
        180f,
        -120f,
        style = Stroke(width = 10f),
        useCenter = false,
        size = Size(120f, 120f),
        topLeft = Offset(nosePathX + 10f, nosePathY)
    )
}
复制代码

画兔唇的时候其实就是在鼻子的两端各画一个坐标轴,左边的兔唇起始角度就是从x轴开始也就是0度,顺时针旋转120度,左上位置的x坐标刚好离开鼻子一个半径的位置,右边的兔唇刚好相反,逆时针旋转120度,起始角度是180度,左上位置的x坐标刚好在鼻子的位置那里,稍微加个10f让兔唇可以对称一些,我们看下效果图

imagen.png

胡须

脸上好像空了点,兔子的胡须还没有呢,胡须其实就是两边各画三条线,用drawLine这个api,起始位置的x坐标跟眼睛中心点的x坐标一样,中间胡须起始位置的y坐标跟鼻子的y坐标一样,上下胡须的y坐标各减去一定的数值

Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) { 
    drawLine(
        color = drawColor,
        start = Offset(leftEyePathX, nosePathY - 60f),
        end = Offset(leftEyePathX - 250f, nosePathY - 90f),
        strokeWidth = 5f,
        cap = StrokeCap.Round
    )
    drawLine(
        color = drawColor,
        start = Offset(leftEyePathX, nosePathY),
        end = Offset(leftEyePathX - 250f, nosePathY),
        strokeWidth = 5f,
        cap = StrokeCap.Round
    )
    drawLine(
        color = drawColor,
        start = Offset(leftEyePathX, nosePathY + 60f),
        end = Offset(leftEyePathX - 250f, nosePathY + 90f),
        strokeWidth = 5f,
        cap = StrokeCap.Round
    )

    drawLine(
        color = drawColor,
        start = Offset(rightEyePathX, nosePathY - 60f),
        end = Offset(rightEyePathX + 250f, nosePathY - 90f),
        strokeWidth = 5f,
        cap = StrokeCap.Round
    )
    drawLine(
        color = drawColor,
        start = Offset(rightEyePathX, nosePathY),
        end = Offset(rightEyePathX + 250f, nosePathY),
        strokeWidth = 5f,
        cap = StrokeCap.Round
    )
    drawLine(
        color = drawColor,
        start = Offset(rightEyePathX, nosePathY + 60f),
        end = Offset(rightEyePathX + 250f, nosePathY + 90f),
        strokeWidth = 5f,
        cap = StrokeCap.Round
    )
}
复制代码

很简单的画了六条线,线的粗细也稍微设置的小一点,毕竟胡须还是比较细的,我们看下效果图

imagen.png

就这样兔子脑袋部分所有元素都画完了,我们接着给兔子画身体

Cuerpo

El cuerpo es en realidad una elipse, su posición es solo un tercio de la parte inferior del lienzo, la coordenada x de la parte superior izquierda es un poco más grande que la coordenada x de la parte superior izquierda de la cabeza, la y- La coordenada es dos tercios del lienzo, y la coordenada x de la esquina inferior derecha es más baja que la coordenada x de la cabeza. Las coordenadas son un poco más pequeñas, y la coordenada y es la parte inferior del lienzo. Después de saberlo, dibujará el cuerpo como la cabeza

val bodyPath = Path()
val bodyPathX = screenWidth() / 2
val bodyPathY = screenHeight() * 5 / 6
bodyPath.moveTo(bodyPathX, bodyPathY)
bodyPath.addOval(
    Rect(
        startX + 50f,
        screenHeight() * 2 / 3,
        screenWidth() - startX - 50f,
        screenHeight()
    )
)
bodyPath.close()
Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) {
    drawPath(path = bodyPath, color = drawColor, style = Stroke(width = 10f))
}
复制代码

Las representaciones son las siguientes

imagen.png

dos garras

Después de dibujar el cuerpo, dibujemos las garras del conejo. Las garras son en realidad dos elipses. La coordenada x del centro de la elipse es la misma que la coordenada x de los dos ojos, y la coordenada y está en cinco- sextos del lienzo.

val leftHandPath = Path()
val leftHandPathX = screenWidth() * 3 / 8
val leftHandPathY = screenHeight() * 5 / 6
leftHandPath.moveTo(leftHandPathX, leftHandPathY)
leftHandPath.addOval(
    Rect(
        leftHandPathX - 35f,
        leftHandPathY - 90f,
        leftHandPathX + 35f,
        leftHandPathY + 90f
    )
)
leftHandPath.close()

val rightHandPath = Path()
val rightHandPathX = screenWidth() * 5 / 8
val rightHandPathY = screenHeight() * 5 / 6
rightHandPath.moveTo(rightHandPathX, rightHandPathY)
rightHandPath.addOval(
    Rect(
        rightHandPathX - 35f,
        rightHandPathY - 90f,
        rightHandPathX + 35f,
        rightHandPathY + 90f
    )
)
rightHandPath.close()
Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) {
    drawPath(path = leftHandPath, color = drawColor, style = Stroke(width = 10f))
    drawPath(path = rightHandPath, color = drawColor, style = Stroke(width = 10f))
}
复制代码

Veamos la representación

imagen.png

Cola

Todavía es el último paso. Dibujemos una cola para el conejo. La coordenada x del punto central de la cola es el ancho del lienzo menos la coordenada del eje x en el lado derecho de la cabeza. La coordenada y del punto central de la cola es la altura del lienzo menos un cierto valor. Veamos el código

val tailPath = Path()
val tailPathX = screenWidth() - startX
val tailPathY = screenHeight() - 200f
tailPath.moveTo(tailPathX, tailPathY)
tailPath.addOval(Rect(tailPathX - 60f, tailPathY - 90f, tailPathX + 60f, tailPathY + 90f))
tailPath.close()
Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) {
    drawPath(path = tailPath, color = drawColor, style = Stroke(width = 10f))
}
复制代码

Acabo de terminar de dibujar un conejo como este, echemos un vistazo a la representación final.

imagen.png

Se ve así, vamos a embellecerlo un poco. Descubrimos que el fondo es un poco monótono. Después de todo, es el Año Nuevo chino. Aunque los fuegos artificiales no están permitidos en muchos lugares, aún podemos echar un vistazo. Encuentra una imagen de fuegos artificiales en Internet y dárselo a Rabbit Vamos a usarlo como fondo. También hay una API como drawImage que puede dibujar imágenes en el lienzo. El código es el siguiente

val bgBitmap = ImageBitmap.imageResource(id = R.drawable.firework_night)
Canvas(
    modifier = Modifier
        .size(screenWidth().dp, screenHeight().dp)
        .background(color = Color.White)
) {
    drawImage(image = bgBitmap,
        srcOffset = IntOffset(0,0),
        srcSize = IntSize(bgBitmap.width,bgBitmap.height),
        dstSize = IntSize(screenWidth().toInt()*5/4,screenHeight().toInt()*5/4),
        dstOffset = IntOffset(0,0)
    )
}
复制代码

Vamos a ver cómo funciona

imagen.png

Hmm~~ Ya terminaste~~ No parece muy atractivo jajaja, pero el punto no es por la estética, sino por una imagen del Año Nuevo chino, y el otro es usar las API de Canvas en Compose.Después En general, a medida que Kotlin madura gradualmente, personalmente creo que es probable que Compose se convierta en el modo de desarrollo de interfaz de usuario principal después de Android.

Finalmente, me gustaría desearles a todos un feliz año nuevo. Les deseo a todos un feliz Año del Conejo, y el "conejo" hará un gran progreso ~~

Supongo que te gusta

Origin juejin.im/post/7186454742950740028
Recomendado
Clasificación