1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
|
// Copyright ©2015 The Gonum Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package vg
import (
"strconv"
"strings"
)
// A Length is a unit-independent representation of length.
// Internally, the length is stored in postscript points.
type Length float64
// Points returns a length for the given number of points.
func Points(pt float64) Length {
return Length(pt)
}
// Common lengths.
const (
Inch Length = 72
Centimeter = Inch / 2.54
Millimeter = Centimeter / 10
)
// Dots returns the length in dots for the given resolution.
func (l Length) Dots(dpi float64) float64 {
return float64(l) / Inch.Points() * dpi
}
// Points returns the length in postscript points.
func (l Length) Points() float64 {
return float64(l)
}
// ParseLength parses a Length string.
// A Length string is a possible signed floating number with a unit.
// e.g. "42cm" "2.4in" "66pt"
// If no unit was given, ParseLength assumes it was (postscript) points.
// Currently valid units are:
// mm (millimeter)
// cm (centimeter)
// in (inch)
// pt (point)
func ParseLength(value string) (Length, error) {
var unit Length = 1
switch {
case strings.HasSuffix(value, "in"):
value = value[:len(value)-len("in")]
unit = Inch
case strings.HasSuffix(value, "cm"):
value = value[:len(value)-len("cm")]
unit = Centimeter
case strings.HasSuffix(value, "mm"):
value = value[:len(value)-len("mm")]
unit = Millimeter
case strings.HasSuffix(value, "pt"):
value = value[:len(value)-len("pt")]
unit = 1
}
v, err := strconv.ParseFloat(value, 64)
if err != nil {
return 0, err
}
return Length(v) * unit, nil
}
|