main.go 2.2 KB
Newer Older
1 2
// Copyright 2010 The Freetype-Go Authors. All rights reserved.
// Use of this source code is governed by your choice of either the
3 4
// FreeType License or the GNU General Public License version 2 (or
// any later version), both of which can be found in the LICENSE file.
5

6 7 8 9 10
// +build ignore
//
// This build tag means that "go install github.com/golang/freetype/..."
// doesn't install this example program. Use "go run main.go" to run it.

11 12 13 14 15 16
package main

import (
	"bufio"
	"fmt"
	"image"
17
	"image/draw"
18 19 20 21
	"image/png"
	"log"
	"os"

N
Nigel Tao 已提交
22
	"github.com/golang/freetype/raster"
23 24 25
)

func p(x, y int) raster.Point {
26 27 28 29
	return raster.Point{
		X: raster.Fix32(x * 256),
		Y: raster.Fix32(y * 256),
	}
30 31 32 33
}

func main() {
	// Draw a rounded corner that is one pixel wide.
34
	r := raster.NewRasterizer(50, 50)
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
	r.Start(p(5, 5))
	r.Add1(p(5, 25))
	r.Add2(p(5, 45), p(25, 45))
	r.Add1(p(45, 45))
	r.Add1(p(45, 44))
	r.Add1(p(26, 44))
	r.Add2(p(6, 44), p(6, 24))
	r.Add1(p(6, 5))
	r.Add1(p(5, 5))

	// Rasterize that curve multiple times at different gammas.
	const (
		w = 600
		h = 200
	)
50
	rgba := image.NewRGBA(image.Rect(0, 0, w, h))
51 52
	draw.Draw(rgba, image.Rect(0, 0, w, h/2), image.Black, image.ZP, draw.Src)
	draw.Draw(rgba, image.Rect(0, h/2, w, h), image.White, image.ZP, draw.Src)
53
	mask := image.NewAlpha(image.Rect(0, 0, 50, 50))
54
	painter := raster.NewAlphaSrcPainter(mask)
N
Nigel Tao 已提交
55
	gammas := []float64{1.0 / 10.0, 1.0 / 3.0, 1.0 / 2.0, 2.0 / 3.0, 4.0 / 5.0, 1.0, 5.0 / 4.0, 3.0 / 2.0, 2.0, 3.0, 10.0}
56
	for i, g := range gammas {
57
		draw.Draw(mask, mask.Bounds(), image.Transparent, image.ZP, draw.Src)
58
		r.Rasterize(raster.NewGammaCorrectionPainter(painter, g))
59
		x, y := 50*i+25, 25
60
		draw.DrawMask(rgba, image.Rect(x, y, x+50, y+50), image.White, image.ZP, mask, image.ZP, draw.Over)
61
		y += 100
62
		draw.DrawMask(rgba, image.Rect(x, y, x+50, y+50), image.Black, image.ZP, mask, image.ZP, draw.Over)
63 64 65
	}

	// Save that RGBA image to disk.
66
	f, err := os.Create("out.png")
67
	if err != nil {
68
		log.Println(err)
69 70 71 72 73 74
		os.Exit(1)
	}
	defer f.Close()
	b := bufio.NewWriter(f)
	err = png.Encode(b, rgba)
	if err != nil {
75
		log.Println(err)
76 77 78 79
		os.Exit(1)
	}
	err = b.Flush()
	if err != nil {
80
		log.Println(err)
81 82 83 84
		os.Exit(1)
	}
	fmt.Println("Wrote out.png OK.")
}