R语言|字符串绘图string2path

2021-10-11 11:16:54 浏览数 (1)

string2path: 提供从字体文件提取字形信息、将轮廓曲线转换为展平路径或细分多边形以及将结果作为data.frame返回的函数.

1、path样式

代码语言:javascript复制
library(string2path)
library(systemfonts)
available_fonts <- systemfonts::system_fonts()$path

# string2path supports only TrueType or OpenType formats 字体
ttf_or_otf <- available_fonts[grepl("\.(ttf|otf)$", available_fonts)]

# string2path() converts a text to paths 
d_path <- string2path("TEXT", ttf_or_otf[12]) 
# > head(d_path)
# # A tibble: 6 x 4
# x     y glyph_id path_id
# <dbl> <dbl>    <dbl>   <dbl>
#   1 0.452 0.505        0       0
# 2 0.451 0.493        0       0
# 3 0.449 0.486        0       0
# 4 0.447 0.482        0       0
# 5 0.446 0.480        0       0
# 6 0.443 0.477        0       0

plot(d_path$x, d_path$y,main = "d_path")

for (p in split(d_path, d_path$path_id)) {
  lines(p$x, p$y)
}

# p = d_path[which(d_path$path_id==1),]
# lines(p$x,p$y)

2、stroke样式

代码语言:javascript复制
# string2stroke() converts a text to strokes
d_stroke <- string2stroke("R", ttf_or_otf[12])
# > head(d_stroke)
# # A tibble: 6 x 5
# x     y glyph_id path_id triangle_id
# <dbl> <dbl>    <dbl>   <dbl>       <dbl>
#   1 0.394 0.404        0       0           0
# 2 0.424 0.403        0       0           0
# 3 0.393 0.397        0       0           0
# 4 0.424 0.403        0       0           1
# 5 0.423 0.394        0       0           1
# 6 0.393 0.397        0       0           1

plot(d_stroke$x, d_stroke$y,main = "d_stroke")

# The stroke is split into triangles, which can be distinguished by `triangle_id`
set.seed(2)
for (p in split(d_stroke, d_stroke$triangle_id)) {
  polygon(p$x, p$y, col = rgb(runif(1), runif(1), runif(1), 0.8))
}

3、填充样式

代码语言:javascript复制
# 填充样式
# string2fill() converts a text to filled polygons
d_fill <- string2fill("TEXT", ttf_or_otf[1])
# > head(d_fill)
# # A tibble: 6 x 5
# x      y glyph_id path_id triangle_id
# <dbl>  <dbl>    <dbl>   <dbl>       <dbl>
#   1 1.10  0             1       1           0
# 2 0.702 0.0756        1       1           0
# 3 1.10  0.0756        1       1           0
# 4 1.25  0             2       2           1
# 5 1.15  0             2       2           1
# 6 1.41  0.223         2       2           1

plot(d_fill$x, d_fill$y,main = "d_fill")

set.seed(2)
for (p in split(d_fill, d_fill$triangle_id)) {
  polygon(p$x, p$y, col = rgb(runif(1), runif(1), runif(1), 0.8))
}

0 人点赞