【Azure Developer】.Net 简单示例 "文字动图显示" Typing to SVG

简介: 【Azure Developer】.Net 简单示例 "文字动图显示" Typing to SVG

问题描述

看见一个有趣的页面,可以把输入的文字信息,直接输出SVG图片,还可以实现动图模式。

示例URL:

https://readme-typing-svg.demolab.com/?font=Fira+Code&pause=1000&color=F7F7F7&background=233911F6&center=true&vCenter=true&random=false&width=435&lines=%E6%8A%8A%E5%AD%97%E5%8F%98%E5%8A%A8%E5%8A%A8%E5%9B%BE%E8%BE%93%E5%87%BA

示例效果:

那么,用.NET API怎么来快速实现这个目的呢?

 

问题解答

通过查看示例URL的Response Headers 和 Body Content,发现其使用的 Content-Type image/svg+xml , 内容使用svg, path, animate, text元素组合而成的HTML代码。

Content-Type(内容类型),一般是指网页中存在的 Content-Type,用于定义网络文件的类型和网页的编码,决定浏览器将以什么形式、什么编码读取这个文件

SVG 意为可缩放矢量图形(Scalable Vector Graphics)。 SVG 使用 XML 格式定义图像。

SVG 路径 - <path> 元素用于定义一个路径。 <path d="M150 0 L75 200 L225 200 Z" /> 它开始于位置150 0,到达位置75 200,然后从那里开始到225 200,最后在150 0关闭路径。

<animate>  随时间动态改变属性

所以是不是只要API的返回体相类似就可以呢?

试验开始

第一步:在Visual Studio 2022中,创建一个.NET Core WEBAPI项目,使用top-level statements.

第二步:设置app.MapGet("/",  ...),添加 httpResponse 参数并在函数体中设置 httpResponse.ContentType = "image/svg+xml"

第三步:直接把示例URL中的全部返回作为 httpResponse  内容输出,F5运行项目测试效果。

app.MapGet("/", async (HttpResponse httpResponse) =>
{
    httpResponse.ContentType = "image/svg+xml";
    string content = "<!-- https://github.com/DenverCoder1/readme-typing-svg/ -->\r\n<svg xmlns='http://www.w3.org/2000/svg'\r\n    xmlns:xlink='http://www.w3.org/1999/xlink'\r\n    viewBox='0 0 435 50'\r\n    style='background-color: #233911F6;'\r\n    width='435px' height='50px'>\r\n                <path id='path0'>\r\n                            <!-- Single line -->\r\n                                <animate id='d0' attributeName='d' begin='0s;d0.end'\r\n                    dur='6000ms' fill='remove'\r\n                    values='m0,25 h0 ; m0,25 h435 ; m0,25 h435 ; m0,25 h0' keyTimes='0;0.66666666666667;0.83333333333333;1' />\r\n                    </path>\r\n    <text font-family='\"Fira Code\", monospace' fill='#F7F7F7' font-size='20'\r\n        dominant-baseline='middle'\r\n        x='50%' text-anchor='middle'>\r\n        <textPath xlink:href='#path0'>\r\n            把字变动动图输出\r\n        </textPath>\r\n    </text>\r\n</svg>\r\n";
    await httpResponse.WriteAsync(content);
    await httpResponse.Body.FlushAsync();
});

测试成功,达到预期的效果。

 

第四步:优化代码,把文本和颜色变为参数

获取 Request中携带的参数 name 和 hex来替换HTML中的文本与颜色值。

PS: 如果有更多的需求,如多行字体,字体,大小,SVG的长宽等,都可以把提取出来变为参数。

完整代码如下:

app.MapGet("/tosvg", async (HttpRequest request, HttpResponse httpResponse) =>
{
    string name = request.Query["name"];
    string colorHex = request.Query["hex"];
   
    name = name ?? "No Name";
    colorHex = colorHex ?? "3943BB";
    httpResponse.ContentType = "image/svg+xml";await httpResponse.WriteAsync(GenerateSVGcontent(name, colorHex));
    await httpResponse.Body.FlushAsync();
});
string GenerateSVGcontent(string name, string colorHex = "#3943BB")
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 200 100' style='background-color:" + colorHex + ";' width='200px' height='100px'>");
    sb.Append("<path id='path0'><animate id='d0' attributeName='d' begin='0s' dur='3000ms' fill='freeze' values='m0,50 h0 ; m0,50 h200 ; m0,50 h200 ; m0,50 h200' keyTimes='0;0.72727272727273;0.81818181818182;1' /></path>");
    sb.Append("<text font-family='\"Arial\", monospace' fill='#FFFFFF' font-size='20' dominant-baseline='middle' x='50%' text-anchor='middle'>");
    sb.Append("<textPath xlink:href='#path0'>");
    sb.Append(name);
    sb.Append("</textPath></text>\r\n</svg>");
    return sb.ToString();
}

第五步:在VS2022中,一键部署到Azure App Service,轻松提供一个HTTP/S API实现文字转动图功能。

 

附录:完整的示例代码

using System.Text; 
var builder = WebApplication.CreateBuilder(args);
 
// Add services to the container.
var app = builder.Build();
app.MapGet("/", async (HttpResponse httpResponse) =>
{
    httpResponse.ContentType = "image/svg+xml";
    string content = "<!-- https://github.com/DenverCoder1/readme-typing-svg/ -->\r\n<svg xmlns='http://www.w3.org/2000/svg'\r\n    xmlns:xlink='http://www.w3.org/1999/xlink'\r\n    viewBox='0 0 435 50'\r\n    style='background-color: #233911F6;'\r\n    width='435px' height='50px'>\r\n                <path id='path0'>\r\n                            <!-- Single line -->\r\n                                <animate id='d0' attributeName='d' begin='0s;d0.end'\r\n                    dur='6000ms' fill='remove'\r\n                    values='m0,25 h0 ; m0,25 h435 ; m0,25 h435 ; m0,25 h0' keyTimes='0;0.66666666666667;0.83333333333333;1' />\r\n                    </path>\r\n    <text font-family='\"Fira Code\", monospace' fill='#F7F7F7' font-size='20'\r\n        dominant-baseline='middle'\r\n        x='50%' text-anchor='middle'>\r\n        <textPath xlink:href='#path0'>\r\n            把字变动动图输出\r\n        </textPath>\r\n    </text>\r\n</svg>\r\n";
    await httpResponse.WriteAsync(content);
    await httpResponse.Body.FlushAsync();
});
app.MapGet("/tosvg", async (HttpRequest request, HttpResponse httpResponse) =>
{
    string name = request.Query["name"];
    string colorHex = request.Query["hex"];
    //name = name:? "Name";
    name = name ?? "No Name";
    colorHex = colorHex ?? "3943BB";
    httpResponse.ContentType = "image/svg+xml";await httpResponse.WriteAsync(GenerateSVGcontent(name, colorHex));
    await httpResponse.Body.FlushAsync();
});
string GenerateSVGcontent(string name, string colorHex = "#3943BB")
{
    StringBuilder sb = new StringBuilder();
    sb.Append("<svg xmlns='http://www.w3.org/2000/svg' xmlns:xlink='http://www.w3.org/1999/xlink' viewBox='0 0 200 100' style='background-color:" + colorHex + ";' width='200px' height='100px'>");
     
    sb.Append("<path id='path0'><animate id='d0' attributeName='d' begin='0s' dur='3000ms' fill='freeze' values='m0,50 h0 ; m0,50 h200 ; m0,50 h200 ; m0,50 h200' keyTimes='0;0.72727272727273;0.81818181818182;1' /></path>");
    //sb.Append("<path id='path0'><animate id='d0' attributeName='d' begin='0s;d0.end' dur='2200ms' fill='remove' values='m0,50 h0 ; m0,50 h200 ; m0,50 h200 ; m0,50 h0' keyTimes='0;0.72727272727273;0.81818181818182;1' /> </path>");
    sb.Append("<text font-family='\"Arial\", monospace' fill='#FFFFFF' font-size='20' dominant-baseline='middle' x='50%' text-anchor='middle'>");
    sb.Append("<textPath xlink:href='#path0'>");
    sb.Append(name);
    sb.Append("</textPath></text>\r\n</svg>");
    return sb.ToString();
}
app.Run();

 

参考资料

Readme Typing SVG : https://readme-typing-svg.demolab.com/demo/

HTTP content-type : https://www.runoob.com/http/http-content-type.html

<animate> : https://www.runoob.com/svg/svg-reference.html

 

相关文章
|
1月前
|
JSON 数据格式
【Azure Fabric Service】演示使用PowerShell命令部署SF应用程序(.NET)
本文详细介绍了在中国区微软云Azure上使用Service Fabrics服务时,通过PowerShell命令发布.NET应用的全过程。由于Visual Studio 2022无法直接发布应用,需借助PowerShell脚本完成部署。文章分三步讲解:首先在Visual Studio 2022中打包应用部署包,其次连接SF集群并上传部署包,最后注册应用类型、创建实例并启动服务。过程中涉及关键参数如服务器证书指纹和服务端证书指纹的获取,并附带图文说明,便于操作。参考官方文档,帮助用户成功部署并运行服务。
129 72
|
1月前
|
存储 XML 开发工具
【Azure Storage Account】利用App Service作为反向代理, 并使用.NET Storage Account SDK实现上传/下载操作
本文介绍了如何在Azure上使用App Service作为反向代理,以自定义域名访问Storage Account。主要内容包括: 1. **设置反向代理**:通过配置`applicationhost.xdt`和`web.config`文件,启用IIS代理功能并设置重写规则。 2. **验证访问**:测试原生URL和自定义域名的访问效果,确保两者均可正常访问Storage Account。 3. **.NET SDK连接**:使用共享访问签名(SAS URL)初始化BlobServiceClient对象,实现通过自定义域名访问存储服务。
|
3月前
|
开发框架 安全 .NET
【Azure Developer】.NET Aspire 项目本地调试遇 Grpc.Core.RpcException 异常( Error starting gRPC call ... )
Error starting gRPC call. HttpRequestException: The SSL connection could not be established, see inner exception. AuthenticationException: The remote certificate is invalid because of errors in the certificate chain: UntrustedRoot
94 12
|
5月前
|
开发框架 监控 .NET
【Azure App Service】部署在App Service上的.NET应用内存消耗不能超过2GB的情况分析
x64 dotnet runtime is not installed on the app service by default. Since we had the app service running in x64, it was proxying the request to a 32 bit dotnet process which was throwing an OutOfMemoryException with requests >100MB. It worked on the IaaS servers because we had the x64 runtime install
|
6月前
|
安全 网络安全 数据安全/隐私保护
【Azure Developer】System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
System.Net.WebException: The request was aborted: Could not create SSL/TLS secure channel.
100 2
|
8月前
|
存储 NoSQL Redis
【Azure Developer】一个复制Redis Key到另一个Redis服务的工具(redis_copy_net8)
【Azure Developer】一个复制Redis Key到另一个Redis服务的工具(redis_copy_net8)
|
8月前
|
监控 Cloud Native 开发者
云端精英的.NET微服务秘籍:Azure上的创新实战演练
【8月更文挑战第28天】在现代软件开发中,微服务架构通过分解应用程序提升可维护性和扩展性。结合Azure与.NET框架,开发者能轻松打造高效且易管理的云原生微服务。首先,使用Docker容器化.NET应用,并借助Azure Kubernetes Service(AKS)或Azure Container Instances(ACI)部署。为确保高可用性和伸缩性,可利用Azure Traffic Manager负载均衡及Azure Autoscale动态调整实例数。
52 0
|
8月前
|
开发框架 .NET C#
【Azure Developer】C# / .NET 静态函数中this关键字的作用
【Azure Developer】C# / .NET 静态函数中this关键字的作用
|
8月前
|
存储 Linux 网络安全
【Azure App Service】.NET代码实验App Service应用中获取TLS/SSL 证书 (App Service Linux/Linux Container)
【Azure App Service】.NET代码实验App Service应用中获取TLS/SSL 证书 (App Service Linux/Linux Container)
下一篇
oss创建bucket