我目前正在使用qazxsw poi库来渲染一些图像。我注意到构建qazxsw poi或qazxsw poi图像的核心算法和方法是相同的。
我需要将此图像渲染为SVG(供Web使用)和PNG(供PDF使用)
唯一的区别在于输入类型和输出。
对于PNG渲染我
作为输入:
draw2d
作为输出:
SVG
对于SVG我:
作为输入:
PNG
作为输出:
var gc *draw2dimg.GraphicContext
var img *image.RGBA
img = image.NewRGBA(image.Rect(0, 0, xSize, ySize))
gc = draw2dimg.NewGraphicContext(img)
输入和输出之间我有相同的实现。
Go中是否有任何方法可以使用不同的输入类型并获得相同的实现而无需复制某些代码?
正如我在评论中提到的,尝试通过将核心算法部分移动到函数中来重构代码,或者可以将其转换为不同的包。为了说明这个想法,下面是draw2dimg.SaveToPngFile(FileName, img)
README中重构的示例。
var gc *draw2dsvg.GraphicContext
var img *draw2dsvg.Svg
img = draw2dsvg.NewSvg()
gc = draw2dsvg.NewGraphicContext(img)
在Go中实现代码共享的典型方法是使用draw2dsvg.SaveToSvgFile(FileName, img)
。看看你是否可以将图像算法的步骤分解为接口方法。然后,这些方法可以通过适用于所有图像格式的单个代码以通用方式驱动,如下面的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)
}
}