How to Write Curved Text

Simple curved text within a circle

As the name implies, a <textPath> must be used with a <path> element. You cannot use it with a <circle>. If you look at the SVG specifications:

In addition to text drawn in a straight line, SVG also includes the ability to place text along the shape of a ‘path’ element. To specify that a block of text is to be rendered along the shape of a ‘path’, include the given text within a ‘textPath’ element which includes an ‘xlink:href’ attribute with an IRI reference to a ‘path’ element.

Note: that's for SVG 1, for SVG 2 see the comment below.

Therefore, you have to create paths. You can convert your circles to paths dealing with the d attribute. For instance, supposing your cx = 100, cy = 100 and r = 30, this would be the d attribute:

d = "M70,100 a 30,30 0 1,0 60,0 a 30,30 0 1,0 -60,0";

There are several online resources explaining how do you calculate the d attribute based on cx, cy and r, like this one.

Here is a demo:

const svg = d3.select("svg");const circle = svg.append("path").style("fill", "none").style("stroke", "black").attr("d", "M70,100 a 30,30 0 1,0 60,0 a 30,30 0 1,0 -60,0");
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script><svg></svg>

How can i make a curved text underline?

You can use :after pseudo-element to hold your underline:

.underlined {  position: relative;  margin-right: 1rem;}.underlined:after {  content: "";  position: absolute;  bottom: -10px;  left: 0;  height: 7px;  width: 100%;  border: solid 2px #cb1829;  border-color: #cb1829 transparent transparent transparent;  border-radius: 50%;}.small {  font-size: 60%;}.big {  font-size: 200%;}
<span class="underlined">Test</span><span class="underlined small">Test</span><span class="underlined big">Test</span>

Curved text Jetpack compose

You can do this using Canvas. Compose itself does not have a function to draw a curved text (afaik in rc-01). But using drawIntoCanvas function you can use the nativeCanvas which provides drawTextOnPath where you can draw a text in a Path. In this Path you add an arc, so your text is drawn in this path.

Canvas(
modifier = Modifier
.size(300.dp)
.background(Color.Gray)
) {
drawIntoCanvas {
val textPadding = 48.dp.toPx()
val arcHeight = 400.dp.toPx()
val arcWidth = 300.dp.toPx()
val path = Path().apply {
addArc(0f, textPadding, arcWidth, arcHeight, 180f, 180f)
}
it.nativeCanvas.drawTextOnPath(
"Curved Text with Jetpack Compose",
path,
0f,
0f,
Paint().apply {
textSize = 16.sp.toPx()
textAlign = Paint.Align.CENTER
}
)
}
}

Here's the result:

Sample Image



Related Topics



Leave a reply



Submit