...

Source file src/gonum.org/v1/plot/font/len.go

Documentation: gonum.org/v1/plot/font

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

View as plain text