我目前正在使用 draw2d lib 来渲染一些图像。我注意到构建 SVG 的核心算法和方法是相同的, 或 PNG图片。
我确实需要将此图像渲染为 SVG(用于 Web)和 PNG(用于 PDF)
唯一的区别在于输入类型和输出。
对于 PNG 渲染我有
作为输入:
var gc *draw2dimg.GraphicContext
var img *image.RGBA
img = image.NewRGBA(image.Rect(0, 0, xSize, ySize))
gc = draw2dimg.NewGraphicContext(img)
作为输出:
draw2dimg.SaveToPngFile(FileName, img)
对于 SVG,我有:
作为输入:
var gc *draw2dsvg.GraphicContext
var img *draw2dsvg.Svg
img = draw2dsvg.NewSvg()
gc = draw2dsvg.NewGraphicContext(img)
作为输出:
draw2dsvg.SaveToSvgFile(FileName, img)
在输入和输出之间我有相同的实现。
在 Go 中是否有任何方法可以使用不同的输入类型并获得相同的实现而无需重复一些代码?
最佳答案
正如我在评论中提到的,尝试通过将核心算法部分移动到函数中或可能移动到不同的包中来重构您的代码。为了说明这个想法,下面是 https://github.com/llgcode/draw2d 中示例的重构版本自述文件。
package main
import (
"image"
"image/color"
"github.com/llgcode/draw2d"
"github.com/llgcode/draw2d/draw2dimg"
"github.com/llgcode/draw2d/draw2dpdf"
"github.com/llgcode/draw2d/draw2dsvg"
)
func coreDraw(gc draw2d.GraphicContext) {
// Set some properties
gc.SetFillColor(color.RGBA{0x44, 0xff, 0x44, 0xff})
gc.SetStrokeColor(color.RGBA{0x44, 0x44, 0x44, 0xff})
gc.SetLineWidth(5)
// Draw a closed shape
gc.BeginPath() // Initialize a new path
gc.MoveTo(10, 10) // Move to a position to start the new path
gc.LineTo(100, 50)
gc.QuadCurveTo(100, 10, 10, 10)
gc.Close()
gc.FillStroke()
}
func main() {
format := "svg"
switch format {
case "png":
dest := image.NewRGBA(image.Rect(0, 0, 297, 210.0))
gc := draw2dimg.NewGraphicContext(dest)
coreDraw(gc)
draw2dimg.SaveToPngFile("hello.png", dest)
case "pdf":
dest := draw2dpdf.NewPdf("L", "mm", "A4")
gc := draw2dpdf.NewGraphicContext(dest)
coreDraw(gc)
draw2dpdf.SaveToPdfFile("hello.pdf", dest)
case "svg":
img := draw2dsvg.NewSvg()
gc := draw2dsvg.NewGraphicContext(img)
coreDraw(gc)
draw2dsvg.SaveToSvgFile("hello.svg", img)
}
}
关于go - Go 中的相同算法、多种输入和输出类型的可能性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49050850/