Giter Club home page Giter Club logo

freetype's People

Contributors

adg avatar fogleman avatar ksimka avatar mattn avatar nigeltao avatar remyoudompheng avatar rogpeppe avatar rsc avatar stephenwithav avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

freetype's Issues

Potential MSIRP implementation issue in hint.go

in hint.go line 671:

curDist := dotProduct(f26dot6(p.X-ref.X), f26dot6(p.Y-ref.Y), h.gs.dv)

as per the specifications:
https://developer.apple.com/fonts/TrueType-Reference-Manual/RM05/Chap5.html#IP

I think the distance should be computed using the projection vector and not the 
dual vector.  (h.gs.pv instead of h.gs.dv)

correct line:
curDist := dotProduct(f26dot6(p.X-ref.X), f26dot6(p.Y-ref.Y), h.gs.pv)

The equivalent code in Freetype is:
distance = CUR_Func_project( CUR.zp1.cur + point,
                                 CUR.zp0.cur + CUR.GS.rp0 );

Where CUR_Func_project use the projection vector:
return TT_DotFix14( (FT_UInt32)dx, (FT_UInt32)dy,
                        CUR.GS.projVector.x,
                        CUR.GS.projVector.y );

Original issue reported on code.google.com by [email protected] on 4 Nov 2014 at 1:38

cmap encoding selection: unicodeEncoding vs. microsoftUCS4Encoding

I'm dumping the glyphs from HanaMinB.ttf
( available at

https://osdn.net/frs/redir.php?m=pumath&f=%2Fhanazono-font%2F64385%2Fhanazono-20160201.zip

), where most of the characters are > U+FFFF.

Enclosed please find the output of
ttfdump -t cmap HanaMinB.ttf

According to the ttfdump output, this ttf file contains 4 cmap
subtables, covering the 4 encodings defined in truetype.go:

unicodeEncoding = 0x00000003 // PID = 0 (Unicode), PSID = 3 (Unicode 2.0)
microsoftSymbolEncoding = 0x00030000 // PID = 3 (Microsoft), PSID = 0 (Symbol)
microsoftUCS2Encoding = 0x00030001 // PID = 3 (Microsoft), PSID = 1 (UCS-2)
microsoftUCS4Encoding = 0x0003000a // PID = 3 (Microsoft), PSID = 10 (UCS-4)

And the current code selects the first one (unicodeEncoding):

pidPsid := u32(table, offset)
// We prefer the Unicode cmap encoding. Failing to find that, we fall
// back onto the Microsoft cmap encoding.
if pidPsid == unicodeEncoding {
bestOffset, bestPID, ok = offset, pidPsid>>16, true
break
} else if pidPsid == microsoftSymbolEncoding ||
pidPsid == microsoftUCS2Encoding ||
pidPsid == microsoftUCS4Encoding {
bestOffset, bestPID, ok = offset, pidPsid>>16, true
// We don't break out of the for loop, so that Unicode can override Microsoft.
}

and none of the >U+FFFF characters are available.

Should we prefer microsoftUCS4Encoding to the
16-bit-only unicodeEncoding ?

HanaMinB.ttf-dump-cmap.txt

Can't get raster.MonochromePainter work

I'm trying to use raster.MonochromePainter, but looks like either it's broken or I'm doing something totally wrong.

I'm using draw2dimg, but that actually doesn't matter, I don't think it's their bug since the only difference is raster.Painter implementation.

Here is an example with simple RGBAPainter.

package main

import (
    "github.com/llgcode/draw2d/draw2dimg"
    "image"
    "image/color"
    "github.com/golang/freetype/raster"
)

type mPainter struct {
    *raster.MonochromePainter
}
func (mp mPainter) SetColor(color color.Color) {
    mp.MonochromePainter.Painter.(*raster.RGBAPainter).SetColor(color)
}

func main() {
    im := image.NewRGBA(image.Rect(0, 0, 100, 100))

    drawPoly := func(col color.RGBA, xys ...int) {
//      painter := raster.NewRGBAPainter(im)
//      painter.SetColor(col)
//      mpainter := mPainter{raster.NewMonochromePainter(painter)}

        gc := draw2dimg.NewGraphicContext(im)
//      gc := draw2dimg.NewGraphicContextWithPainter(im, mpainter)
        gc.SetFillColor(col)
        gc.SetStrokeColor(col)
        gc.SetLineWidth(0)

        gc.MoveTo(float64(xys[0]), float64(xys[1]))
        for i := 2; i < len(xys); i += 2 {
            gc.LineTo(float64(xys[i]), float64(xys[i+1]))
        }
        gc.LineTo(float64(xys[0]), float64(xys[1]))
        gc.Close()
        gc.Fill()
    }

    drawPoly(color.RGBA{0, 200, 0, 150}, 10, 10, 60, 10, 60, 60, 10, 60)
    drawPoly(color.RGBA{200, 0, 0, 150}, 20, 20, 70, 20, 70, 70, 20, 70)

    draw2dimg.SaveToPngFile("test.png", im)
}

It outputs expected image.

test

And here is an example with MonochromePainter which description is

// A MonochromePainter wraps another Painter, quantizing each Span's alpha to
// be either fully opaque or fully transparent.
package main

import (
    "github.com/llgcode/draw2d/draw2dimg"
    "image"
    "image/color"
    "github.com/golang/freetype/raster"
)

type mPainter struct {
    *raster.MonochromePainter
}
func (mp mPainter) SetColor(color color.Color) {
    mp.MonochromePainter.Painter.(*raster.RGBAPainter).SetColor(color)
}

func main() {
    im := image.NewRGBA(image.Rect(0, 0, 100, 100))

    drawPoly := func(col color.RGBA, xys ...int) {
        painter := raster.NewRGBAPainter(im)
        painter.SetColor(col)
        mpainter := mPainter{raster.NewMonochromePainter(painter)}

//      gc := draw2dimg.NewGraphicContext(im)
        gc := draw2dimg.NewGraphicContextWithPainter(im, mpainter)
        gc.SetFillColor(col)
        gc.SetStrokeColor(col)
        gc.SetLineWidth(0)

        gc.MoveTo(float64(xys[0]), float64(xys[1]))
        for i := 2; i < len(xys); i += 2 {
            gc.LineTo(float64(xys[i]), float64(xys[i+1]))
        }
        gc.LineTo(float64(xys[0]), float64(xys[1]))
        gc.Close()
        gc.Fill()
    }

    drawPoly(color.RGBA{0, 200, 0, 150}, 10, 10, 60, 10, 60, 60, 10, 60)
    drawPoly(color.RGBA{200, 0, 0, 150}, 20, 20, 70, 20, 70, 70, 20, 70)

    draw2dimg.SaveToPngFile("test.png", im)
}

It outputs empty (white backgroung) image. And even if I change alpha of fill color to 255, nothing changes. Actually, with any color I get white image like all the things are transparent.

Can you please help me with this? I can try to debug if you tell me where to look.

Cyrrilic text for image

Hello! I need to create cyrillic text in image but all I can get is squares. Here is my code

package main

import (
    "github.com/jung-kurt/gofpdf"
    "github.com/golang/freetype"
    "image"
    "fmt"
    "os"
    "bytes"
    "image/jpeg"
    "io/ioutil"
    "image/draw"
)

func main() {
    pwd, err := os.Getwd()
    if err != nil {
        fmt.Println(err)
        os.Exit(1)
    }
    dataFont, err := ioutil.ReadFile(pwd + "/font/luxisr.ttf")
    if err != nil {
        fmt.Printf("%v",err)
    }
    f, err := freetype.ParseFont(dataFont)
    if err != nil {
        fmt.Printf("%v",err)
    }
    dst := image.NewRGBA(image.Rect(0, 0, 800, 600))
    draw.Draw(dst, dst.Bounds(), image.White, image.ZP, draw.Src)
    c := freetype.NewContext()
    c.SetDst(dst)
    c.SetClip(dst.Bounds())
    c.SetSrc(image.Black)
    c.SetFont(f)
    c.DrawString("русский текст", freetype.Pt(0, 16))
    pdf := gofpdf.New("P", "mm", "A4", "")
    pdf.AddPage()
    buf := new(bytes.Buffer)
    err = jpeg.Encode(buf, dst, nil)

    if err != nil {
        fmt.Printf("%v",err)
    }

    reader := bytes.NewReader(buf.Bytes())
    textName := "text1"
    pdf.RegisterImageReader(textName, "jpg", reader)
    pdf.Image(textName, 15, 15, 0, 0, false, "jpg", 0, "")
    pdf.OutputFileAndClose("test.pdf")
}

Fix TTC parsing

I have no idea how to submit patches, so forgive me if this is an inappropriate 
venue.

Attached is a patch fixing TTC parsing.
The constant 12 was hardcoded instead of using `offset`.

Tested on a TTC v2.0 file, I don't have a v1.0 file to test on but based on 
what I understand of the file format I don't think there should be any issues 
with that.

Original issue reported on code.google.com by [email protected] on 10 Sep 2014 at 4:30

Attachments:

DeltaP / DeltaC implementation questions

the line 1346 - 1347 looks weird 
1346 n := f26dot6(h.stack[top])

This may be pedantic, but "n" in this case is a counter used for the loop at 
line 1350: "for ; n > 0; n--"
It is in no way a 26.6 fixed point value so why cast it to f26dot6 ?
------
line 1347  if top < 2*int(h.gs.loop) { 
This may be a copy/paste error, I don't see how the gs.loop value has anything 
to do with deltaP or deltaC.
I'm assuming you want:
line 1347  if top < 2*n { 

Original issue reported on code.google.com by [email protected] on 5 Nov 2014 at 8:45

SetSrc only makes sense if it's image.Uniform

What steps will reproduce the problem?
1. Use a non-image.Uniform image in SetSrc.
2. Call freetype.DrawString

What is the expected output? What do you see instead?
I'd expect that the src passed to c.SetSrc gets composited with the destination 
with the two images aligned.

Instead, for each glyph, a region (0, 0) to (w, h) gets used from src, where w, 
h are the dimensions of the glyph, with the result that the actual colors taken 
from src depending on the height of the rendered glyph and adjacent glyphs are 
inconsistently colored.

What version of the product are you using? On what operating system?
Lion on mac, but I'm sure that's irrelevant.


Please provide any additional information below.

In: http://code.google.com/p/freetype-go/source/browse/freetype/freetype.go#212
I think image.ZP should be dr.Min, or possibly adjusted to align src.Min and 
dst.Min.
The comment would need fixing too to specify the meaning of the SetSrc value.

Attached is a variant of one of the example files that exhibits the problem. 
I've tried to make the colors as nasty as possible to make the problem visible. 
I've also attached a png with the output.

Original issue reported on code.google.com by [email protected] on 1 Aug 2012 at 7:56

Attachments:

Is it possible to use color.Model when rasterizing?

Hello,
this is kinda of a feature request, but also a request for clarification because maybe I just got things wrong.
I am trying to work on go-sdl2 so that SDL Surfaces implements go's image.Image and image/draw.Image interfaces. The idea is to be able to render directly on SDL surfaces. After making such changes and trying to use freetype raster's on that surfaces, I noticed that there are a certain number of painters, each of which is working with a specific image format.

Now, I find this confusing: isn't image/color.Model there to perform color conversion from one model to another? So, my question boils down to: why isn't there a painter which can deal with a generic image/draw.Image and use its color model to map the pixels produced by rasterizer to whatever color format the image is using? Is this feasible at all or did I get all wrong?

I thought that, given a certain color you wanted to draw on the image, one could just do img.Set(img.ColorModel().Convert(your_color)). Is a painter like this possible to have?

Thanks!

Install error in my ubuntu 11.04

cm@ubuntu:~/go/src/pkg/github.com/chsc/gogl$ sudo /home/cm/go/bin/go get 
code.google.com/p/freetype-go/freetype
package code.google.com/p/freetype-go/freetype
    imports fmt: unrecognized import path "fmt"
package code.google.com/p/freetype-go/freetype
    imports image: unrecognized import path "image"
package code.google.com/p/freetype-go/freetype
    imports image/color: unrecognized import path "image/color"
package code.google.com/p/freetype-go/freetype
    imports image/draw: unrecognized import path "image/draw"
package code.google.com/p/freetype-go/freetype
    imports math: unrecognized import path "math"
package code.google.com/p/freetype-go/freetype
    imports runtime: unrecognized import path "runtime"
package code.google.com/p/freetype-go/freetype
    imports strconv: unrecognized import path "strconv"
package code.google.com/p/freetype-go/freetype
    imports errors: unrecognized import path "errors"


Original issue reported on code.google.com by [email protected] on 14 Oct 2012 at 10:34

Neither release go or weekly go will compile/install...

From a Go synced/built from "release" branch:

$ goinstall freetype-go.googlecode.com/hg/freetype
/bin/bash: === cd 
/home/shutej/go/src/pkg/freetype-go.googlecode.com/hg/freetype/raster; bash 
gomake -f- install
6g  -o _go_.6 geom.go paint.go raster.go stroke.go 
paint.go:65: cannot convert c (type image.AlphaColor) to type int
paint.go:66: cannot use uint8((v * 255 + (255 - v) * a) / 255) (type uint8) as 
type image.AlphaColor in assignment
paint.go:105: cannot use color (type uint8) as type image.AlphaColor in 
assignment
paint.go:150: cannot convert r.Image.Pix[i + 0] (type image.RGBAColor) to type 
uint32
paint.go:151: cannot convert r.Image.Pix[i + 1] (type image.RGBAColor) to type 
uint32
paint.go:152: cannot convert r.Image.Pix[i + 2] (type image.RGBAColor) to type 
uint32
paint.go:153: cannot convert r.Image.Pix[i + 3] (type image.RGBAColor) to type 
uint32
paint.go:155: cannot use uint8((dr * a + r.cr * ma) / m >> 8) (type uint8) as 
type image.RGBAColor in assignment
paint.go:156: cannot use uint8((dg * a + r.cg * ma) / m >> 8) (type uint8) as 
type image.RGBAColor in assignment
paint.go:157: cannot use uint8((db * a + r.cb * ma) / m >> 8) (type uint8) as 
type image.RGBAColor in assignment
paint.go:157: too many errors
make: *** [_go_.6] Error 1
--- exit status 2
goinstall: installing: running bash: exit status 2

Original issue reported on code.google.com by [email protected] on 14 Jul 2011 at 3:44

Index out of range

I had a panic occur in production today, this could be related to some of the bugs found in #17. It appears to stem from

dy := int16(glyf[offset])

The stack trace is attached below
chrome_2018-09-12_13-48-53

I am not sure exactly what produced this bug, and normally the function that gets run doesn't produce this error. However, this could be an indication that there needs to be some checking before assuming that the offset is a valid index?

Fallback fonts

How would I go about handling fallback fonts? Say I want to "write" a string with both japanese and latin characters, but the font I loaded only contains loaded characters. Would it somehow be possible to merge two truetype.Fonts into one?

Expose ascent and descent in truetype.Font.

These are needed to figure out line height and the height for the background of 
highlighted text. Font.Bounds().YMin and YMax don't work; they are too large. 
Instead we need ascent and descent from the hhea table.

Original issue reported on code.google.com by [email protected] on 16 Feb 2015 at 8:13

Artifacts close to start/end points


Freetype-go generates artifacts close to start and end path points,
output differs from Freetype-C.

Font is automatically converted from C to Q by FontForge, no problems detected.
Rearanged canonical start point to leftmost on the contour produces expected 
output.


Original issue reported on code.google.com by [email protected] on 20 Feb 2015 at 9:48

Attachments:

truetype: font metrics ascent and descent values appear incorrect

I believe this is related to #32 where eaburns pointed out a potential issue with the scale factor. I don't know a great deal about fonts, but presuming a zero line gap and that height == ascent+descent, I'm seeing issues with Droid Sans and Source Code Pro fonts using font.Drawer, no hinting, 72dpi, 240pt.

For example:

bin, err := ioutil.ReadFile("DroidSans.ttf")
if err != nil {
    log.Fatal(err)
}
f, err := truetype.Parse(bin)
if err != nil {
    log.Fatal(err)
}

fc := truetype.NewFace(f, &truetype.Options{
    Size:    240,
    DPI:     72,
    Hinting: font.HintingNone,
})

fmt.Printf("metrics %+v\n", fc.Metrics())
// Output: metrics {Height:240:00 Ascent:222:50 Descent:56:39}
fmt.Printf("ascent+descent %v\n", fc.Metrics().Ascent+fc.Metrics().Descent)
// Output: ascent+descent 279:25

I'm packing glyphs in a texture and exporting the metrics for use in opengl. The above was causing my baseline calculation to be lower than expected. For now I've worked around this by scaling the ascent and descent by size/(ascent+descent) which produced the semi-correct result I'd expect.

[Question] about Metrics.Height

Hi, we are using this library for g3n and it's working nicely.
We just started using font metrics (thanks for adding that 😄) to better position text and it simplified the math since the metrics already take into account the point size and DPI.

For all the fonts I tried, I noticed that Metrics.Height < Metrics.Ascent + Metrics.Descent. Why is that the case? I know that the docs state that "Height is the recommended amount of vertical space between two lines of text" but shouldn't that be the same as the height of the font?

The only difference I see between how Height is calculated and the other metrics is that it is not divided by fUnitsPerEm.

Thanks in advance!

Text extents

With freetype-go, is there a way to compute the text extents (width and height) 
of a string given a particular font and size *before* rendering the text?

I've looked around in the source code, and it *appears* that the right 
information is there, but I can't quite seem to figure out how to do it.

As of right now, if I want an image that "snugly" fits some string, I do the 
following:

Over estimate the extents by multiplying the pixel size of one em unit by the 
length of the string. I get the width/height this way (assuming one line of 
text).

I allocate an image with a rectangle of two points: (0, 0) and (width, height).

After rendering the text to the image using DrawText, I use the point returned 
from DrawText to take a sub-image of the initial image. (I convert this point 
to a (x, y) position by simply dividing the X and Y of the point by 256. It 
seems to work OK, but I have no idea if this is correct.)

--------------

And one last question: would the extents include the entire bounding box of the 
string? The (x,y) position returned by DrawText doesn't seem to cover the parts 
of the text the dip below the text's base line. Like the tail in the 'y'. My 
solution has just been to pad the 'y' with a few pixels, but I know this is not 
optimal since it will break if the font size changes too much.

(My apologies if my terminology is off. I don't have much experience in font 
rendering.)

I would happily submit a patch if I was nudged in the right direction :-)

Thanks!

Original issue reported on code.google.com by [email protected] on 2 Jun 2012 at 10:44

`dep ensure` fails

When I tried to add firebase.google.com/go using dep, following error occurred:

$ dep ensure -add firebase.google.com/go
The following errors occurred while deducing packages:
  * "code.google.com/p/freetype-go/freetype/raster": unable to deduce repository and source type for "code.google.com/p/freetype-go/freetype/raster": unable to read metadata: go-import metadata not found

validateParams: could not deduce external imports' project roots

I'm not sure the issue relates to this repository, http://code.google.com/p/freetype-go/freetype/raster redirects to this repository.

environment

$ dep version
dep:
 version     : v0.4.1
 build date  : 2018-01-27
 git hash    : 37d9ea0
 go version  : go1.9.3
 go compiler : gc
 platform    : darwin/amd64

go get github.com/golang/freetype failed

go get github.com/golang/freetype

package golang.org/x/image/math/fixed: unrecognized import path "golang.org/x/im
age/math/fixed"
package golang.org/x/image/font: unrecognized import path "golang.org/x/image/fo
nt"

Adjust the font centered in the image

Font centered in the image

For example:

pt := freetype.Pt(0,440 + int(f.PointToFixed(26)) >> 8) 

That is, how to quickly and automatically give the X coordinate value so that the font is centered.

Music Symbol for image

I try to put output some music symbol just like the example but fail
anyone can help?

aguai@Sherlock:example/freetype>>$ cat main.go                                       =03-06 00:31=
// Copyright 2010 The Freetype-Go Authors. All rights reserved.
// Use of this source code is governed by your choice of either the
// FreeType License or the GNU General Public License version 2 (or
// any later version), both of which can be found in the LICENSE file.

// +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.

package main

import (
    "bufio"
    "flag"
    "fmt"
    "image"
    "image/color"
    "image/draw"
    "image/png"
    "io/ioutil"
    "log"
    "os"

    "github.com/golang/freetype"
    "golang.org/x/image/font"
)

var (
    dpi      = flag.Float64("dpi", 72, "screen resolution in Dots Per Inch")
    fontfile = flag.String("fontfile", "./HanaMinA.ttf", "filename of the ttf font")
    hinting  = flag.String("hinting", "none", "none | full")
    size     = flag.Float64("size", 48, "font size in points")
    spacing  = flag.Float64("spacing", 1.5, "line spacing (e.g. 2 means double spaced)")
    wonb     = flag.Bool("whiteonblack", false, "white text on a black background")
)

var text = []string{
    "руссий текст",
        "𝄝𝄞𝄟𝄠𝄡𝄢𝄣𝄤𝄥 ",
    "亂入啊亂入",
    "One, two! One, two! and through and through"
}

func main() {
    flag.Parse()

    // Read the font data.
    fontBytes, err := ioutil.ReadFile(*fontfile)
    if err != nil {
        log.Println(err)
        return
    }
    f, err := freetype.ParseFont(fontBytes)
    if err != nil {
        log.Println(err)
        return
    }

    // Initialize the context.
    fg, bg := image.Black, image.White
    ruler := color.RGBA{0xdd, 0xdd, 0xdd, 0xff}
    if *wonb {
        fg, bg = image.White, image.Black
        ruler = color.RGBA{0x22, 0x22, 0x22, 0xff}
    }
    rgba := image.NewRGBA(image.Rect(0, 0, 1600, 1000))
    draw.Draw(rgba, rgba.Bounds(), bg, image.ZP, draw.Src)
    c := freetype.NewContext()
    c.SetDPI(*dpi)
    c.SetFont(f)
    c.SetFontSize(*size)
    c.SetClip(rgba.Bounds())
    c.SetDst(rgba)
    c.SetSrc(fg)
    switch *hinting {
    default:
        c.SetHinting(font.HintingNone)
    case "full":
        c.SetHinting(font.HintingFull)
    }

    // Draw the guidelines.
    for i := 0; i < 200; i++ {
        rgba.Set(10, 10+i, ruler)
        rgba.Set(10+i, 10, ruler)
    }

    // Draw the text.
    pt := freetype.Pt(10, 10+int(c.PointToFixed(*size)>>6))
    for _, s := range text {
        _, err = c.DrawString(s, pt)
        if err != nil {
            log.Println(err)
            return
        }
        pt.Y += c.PointToFixed(*size * *spacing)
    }

    // Save that RGBA image to disk.
    outFile, err := os.Create("out.png")
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }
    defer outFile.Close()
    b := bufio.NewWriter(outFile)
    err = png.Encode(b, rgba)
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }
    err = b.Flush()
    if err != nil {
        log.Println(err)
        os.Exit(1)
    }
    fmt.Println("Wrote out.png OK.")
}

Right-to-Left Languages

How can freetype be used with RTL languages?

It renders the letters only in their capital form and draw them left to right.

OpenSans font compatability

It seems that the truetype package cannot load the OpenSans font.

The font is compatible with other TTF viewers/editors.. so I wonder why I 
receive this error (from freetype.ParseFont() function):

freetype: invalid TrueType format: bad kern table length

Download font at www.opensans.com, I used the OpenSans-Regular.ttf font, but it 
seems all the OpenSans fonts do not parse properly.

Best regards,
Stephen

Original issue reported on code.google.com by [email protected] on 26 May 2013 at 4:47

FullHinting and PointToFix32

I upgraded the package and now I am missing freetype.FullHinting and freetype.NewContext().PointToFix32. How to fix this?

ui: slide{Up,Down,Left,Right} should slide as much as possible.

Right now these four functions try to slide by the given delta value. If they cannot slide by that amount, they don't move and return false. Instead, they should try to slide as much as possible up to delta. This has two benefits: 1) often if each frame slides a bit, it can amount to enough further up the recursion stack, 2) frames will be able to slide flush with the side of the window.

Combining / Non-spacing characters don't work correctly

When I use this module to print text to an image file, everything seems to work correctly.
However, in a special case, I want to underline some characters, I tried to use the Combining / Non-spacing character \u0332 for that, but it just comes out as a separate character. There are quite some combining / non-spacing characters, check: http://www.fileformat.info/info/unicode/category/Mn/list.htm

Here's the result:
selection_988

(the text on the right should be underlined)

I tried to look into the code to pinpoint the issue, but the code is a little too advanced for me to understand it in a quick look but I'm pretty sure it's in func (g *GlyphBuf) Load(f *Font, scale fixed.Int26_6, i Index, h font.Hinting) error { in truetype/glyph.go, where it calculates the advanceWidth. The font I'm using is DejaVu Sans Mono and DejaVu Sans Mono Bold.

unable to get glyph bounding box

It is currently not possible to get the bounding box of a specific glyph, and 
thus one can't figure out all the metrics one might need. Please add something 
like func (f *Font) Bounds(scale int32, i Index) Bounds.

Original issue reported on code.google.com by [email protected] on 7 Feb 2015 at 1:38

[QUESTION] Can Rasterizer be used to rasterize a horizontal line into spans?

I used the following code to rasterize a horizontal Line, but the output is empty! Is this my mistake or there's a bug in Rasterizer?

type painter struct {

}

func (p *painter) Paint(spans []raster.Span, done bool) {
	for _, span := range spans {
		fmt.Printf("span %d, %d, %d\n", span.Y, span.X0, span.X1)
	}
}

func main() {
	raster := raster.NewRasterizer(256, 256)
	raster.UseNonZeroWinding = true
	raster.Start(fixed.Point26_6{fixed.Int26_6(10 * 64), fixed.Int26_6(10 * 64)})
	raster.Add1( fixed.Point26_6{fixed.Int26_6(50 * 64), fixed.Int26_6(10 * 64)})
	var ptr painter
	raster.Rasterize(&ptr);
}

rendering simple/small fonts on small LCD

I have an application where I'd like to render the tight pixel font (https://www.dafont.com/tight-pixel.font) on a small 128x64 LCD with a 1-bit color space. Attached is an image showing the font rendered with golang/freetype (the example program), and gimp. I'd like it to look more like the gimp rendering (with no anti-aliasing, etc). Is there any way to do this with golang/freetype?

I've also looked at https://github.com/pbnjay/pixfont and it works OK, but it has an issue with calculating string width of using variable width fonts, plus it is more work to use the font.

Appreciate any pointers.

(note, most browsers and image viewers smooth the below image, so it is best viewed in gimp if you want to see exactly what is going on at the pixel level)

tight-pixel-rendering

42 crashers

The attached archive contains 42 unique crashers for the package. The test 
inputs were passed through the following program:
http://play.golang.org/p/qxzq2QBtYx
The headers of crashes are provided below. Each one of them is unique, i.e. 
crash with a unique panic message and/or at different stack. I physically can't 
file separate issue for each individual crash. Some of the inputs are valid 
TTFs files taken elsewhere.

panic: runtime error: invalid memory address or nil pointer dereference
panic: truetype: hinting: division by zero
panic: truetype: hinting: nested FDEF
panic: runtime error: index out of range
panic: runtime error: index out of range
panic: truetype: hinting: point out of range
panic: truetype: hinting: invalid data
panic: truetype: hinting: undefined function
panic: runtime error: index out of range
panic: truetype: hinting: unimplemented twilight point adjustment
panic: truetype: hinting: unbalanced FDEF
panic: truetype: hinting: call stack underflow
panic: runtime error: index out of range
panic: truetype: hinting: stack underflow
panic: runtime error: invalid memory address or nil pointer dereference
panic: truetype: hinting: insufficient data
panic: runtime error: index out of range
panic: truetype: hinting: unrecognized instruction
panic: freetype: unsupported TrueType feature: negative number of contours
panic: runtime error: index out of range
panic: truetype: hinting: stack overflow
panic: runtime error: index out of range
panic: truetype: hinting: unbalanced IF or ELSE
panic: runtime error: slice bounds out of range
panic: runtime error: index out of range
panic: freetype: unsupported TrueType feature: compound glyph transform vector
panic: runtime error: index out of range
panic: runtime error: slice bounds out of range
panic: truetype: hinting: too many instructions
panic: runtime error: invalid memory address or nil pointer dereference
panic: runtime error: integer divide by zero
panic: truetype: hinting: contour out of range
panic: truetype: hinting: unsupported IDEF instruction
panic: runtime error: integer divide by zero
panic: runtime error: integer divide by zero
panic: hinting: unimplemented SHC instruction
panic: runtime error: slice bounds out of range
panic: runtime error: integer divide by zero
panic: runtime error: index out of range
panic: runtime error: index out of range
panic: runtime error: index out of range
panic: runtime error: index out of range

Original issue reported on code.google.com by [email protected] on 29 Apr 2015 at 10:25

Attachments:

Vertical Text

Is there a way to set a text in vertical?

I'd really appreciate that...

Thanks

raster: stroking unsupported on cubic bezier segments (Add3)

Stroking is unsupported on cubic bezier path segments:
// Add3 adds a cubic segment to the stroker.
func (k *stroker) Add3(b, c, d fixed.Point26_6) {
panic("freetype/raster: stroke unimplemented for cubic segments")
}

There could be 3 alternatives to fix this:

A- Linear flattening: divide the cubic segment into several linear segments before stroking - can be implemented through simple heuristics or through a more evolved subdivision (e.g., http://www.cis.usouthal.edu/~hain/general/Publications/Bezier/BezierFlattening.pdf)

B- Quadratic approx.: subdivide into quadratic segments and stroke them

C- Cubic shifting: subdivide into cubic segments until they are "flat" enough that a simple offset translation is sufficient to generate the stroke curves.

Going forward would require to:
(1) Identify through the litterature the best alternative in terms of rendering quality + execution speed
(2) Implement it

I don't have enough spare time for (1) (already reading 10+ machine learning papers per day!). But, regarding (2), I could implement a simple variant of A (simple subdivisions). B or C would be way too much for my spare time, unless a simple algorithm can be unearthed.

Parsing Chinese Font not showing its font name

When I tried to get font's name with truetype.Parse I can't get the font's name / family name in english. It shows up as ????? instead of its english name.

Here is my go code:
ttfParsed, err := truetype.Parse(filePath) if(err != nil) { continue } fmt.Println(">> "+ttfParsed.Name(1)+" | -->"+fontName)

I tried ttfParsed.Name with value 1, 2, 3, 16, and 17 all showed up as '?????' - please refers to the image below.
image

Using fonts: Microsoft Jhenghei (https://www.fontsmarket.com/font-download/microsoft-jhenghei)
Environment: go version go1.9.4 windows/amd64 on Windows 10

How do I get the english name of non-english font?

undefined: font.Metrics

cmd:go get github.com/golang/freetype

github.com/golang/freetype/truetype

../../../golang/freetype/truetype/face.go:254: undefined: font.Metrics
../../../golang/freetype/truetype/face.go:257: undefined: font.Metrics

image

how to resolve this problem?

Easier packaging

Hi, I'm currently packaging Go and several modules including this one. Is there 
any reason to have that much AUTHORS / LICENSE / README files? I'd prefer to 
have only those on the top-level. 

Furthermore, the aes and twofish subdirs dont' have working Makefiles, so 
they're currently ignore for package builds. Plans to fix?

Original issue reported on code.google.com by [email protected] on 9 Nov 2010 at 8:40

what is the proper way of setting text color ?

I am trying to set the text color based on the example provided here. https://github.com/golang/freetype/blob/master/example/freetype/main.go

I don't see any code that explicitly sets the color of the text, except this:

ruler := color.RGBA{0xdd, 0xdd, 0xdd, 0xff}
	if *wonb {
		fg, bg = image.White, image.Black
		ruler = color.RGBA{0x22, 0x22, 0x22, 0xff}
	}

//... and then later

	// Draw the guidelines.
	for i := 0; i < 200; i++ {
		rgba.Set(10, 10+i, ruler)
		rgba.Set(10+i, 10, ruler)
	}

I tried this in my code, but it does not seem to change the color of the text. What is the proper way of doing so. Thanks.

Image coming out blurry when drawing text over it

I have created a composite image using a background single-color png image and 
a text overlay using freetype-go. However, as you can see from the attached 
image file, some of the color below the image is coming out blurred. Can anyone 
tell me what I am doing wrong? Below is the code I am using to create the image.

func getImage(c *context, imageText string) (*image.RGBA, error) {
    colors := []string{"blue", "green", "orange", "red"}

    flag.Parse()
    //read the image file
    reader, err := os.Open("poll_image_" + colors[rand.Intn(len(colors))] + ".png")
    if err != nil {
        return nil, err
    }
    src, _, err := image.Decode(reader)
    if err != nil {
        return nil, err
    }
    b := src.Bounds()
    rgba := image.NewRGBA(image.Rect(0, 0, *imagewidth, *imageheight))
    draw.Draw(rgba, rgba.Bounds(), src, b.Min, draw.Src)
    // Read the font data.
    fontBytes, err := ioutil.ReadFile(*fontfile)
    if err != nil {
        return nil, err
    }
    font, err := freetype.ParseFont(fontBytes)
    if err != nil {
        return nil, err
    }
    // Initialize the context.
    fg := image.White
    ftc := freetype.NewContext()
    ftc.SetHinting(freetype.NoHinting)
    ftc.SetDPI(*dpi)
    ftc.SetFont(font)
    ftc.SetClip(rgba.Bounds())
    ftc.SetDst(rgba)
    ftc.SetSrc(fg)

    // Draw the text.
    sz := *fontsize
    pt := freetype.Pt(*imageleftmargin, *imagetopmargin+int(ftc.PointToFix32(sz)>>8))
    ftc.SetFontSize(sz)
    lines := getImageTextLines(imageText)
    for _, line := range lines {
        _, err = ftc.DrawString(line, pt)
        if err != nil {
            return nil, err
        }
        pt.Y += ftc.PointToFix32(sz * *linespacing)
    }
    return rgba, nil
}

Original issue reported on code.google.com by [email protected] on 10 May 2015 at 5:34

Attachments:

RoundCapper seems to be "working in reverse", shape is spiky not round

out

package main

import (
    "image"
    "image/png"
    "log"
    "os"

    "github.com/golang/freetype/raster"
    "golang.org/x/image/math/fixed"
)

func main() {
    const (
        w = 400
        h = 400
    )
    var p raster.Path
    p.Start(fixed.P(150, 150))
    p.Add1(fixed.P(200, 250))
    p.Add1(fixed.P(300, 250))

    r := raster.NewRasterizer(w, h)
    r.UseNonZeroWinding = true
    r.AddStroke(p, fixed.I(80), raster.RoundCapper, raster.RoundJoiner)

    rgba := image.NewRGBA(image.Rect(0, 0, w, h))
    painter := raster.NewRGBAPainter(rgba)
    painter.SetColor(image.Black)
    r.Rasterize(painter)

    f, err := os.Create("out.png")
    if err != nil {
        log.Fatalf("cannot create file: %v", err)
    }
    defer f.Close()
    if err := png.Encode(f, rgba); err != nil {
        log.Fatalf("writing png: %v", err)
    }
    if err := f.Close(); err != nil {
        log.Fatalf("closing file: %v", err)
    }
}

join/cap stroke polyline


When stroking polyline with a path, lines are not joined very well 
(see the Attached screenshot, line width is 20) 

I think this is a bug.
below you can see a short extract of the code(gc mean graphic context) that 
stroke a rectangle
func (gc *GC) StrokeRect(line [4]float) { 
        gc.path.Start(toPoint(line[0], line[1])) 
        gc.path.Add1(toPoint(line[2], line[1])) 
        gc.path.Add1(toPoint(line[2], line[3])) 
        gc.path.Add1(toPoint(line[0], line[3])) 
        gc.path.Add1(toPoint(line[0], line[1])) 
        raster.Stroke(gc.rasterizer, gc.path, raster.Fix32(gc.lineWidth*256), nil, nil) 
        b := gc.image.Bounds() 
        mask := image.NewAlpha(b.Dx(), b.Dy()) 
        painter := raster.NewAlphaOverPainter(mask) 
        gc.rasterizer.Rasterize(painter) 
        strokeColor := image.NewColorImage(gc.strokeColor) 
        draw.DrawMask(gc.image, gc.image.Bounds(), strokeColor, image.ZP, mask, image.ZP, draw.Over) 
        gc.rasterizer.Clear() 
        gc.path.Clear() 
} 

func toPoint(x, y float) raster.Point { 
        return raster.Point{raster.Fix32(int(x * 256)), raster.Fix32(int(y * 256))} 
} 


Original issue reported on code.google.com by [email protected] on 14 Nov 2010 at 8:36

Attachments:

goinstall: image/draw

goinstall cannot find the image/draw package with the latest release of Go. It 
appears the package is actually @ /go/src/pkg/exp/draw

Original issue reported on code.google.com by [email protected] on 10 Jun 2011 at 11:08

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.