shapes.go (2203B)
1 // Copyright 2017 The Ebiten Authors 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package ebitenutil 16 17 import ( 18 "image" 19 "image/color" 20 "math" 21 22 "github.com/hajimehoshi/ebiten/v2" 23 ) 24 25 var ( 26 emptyImage = ebiten.NewImage(3, 3) 27 emptySubImage = emptyImage.SubImage(image.Rect(1, 1, 2, 2)).(*ebiten.Image) 28 ) 29 30 func init() { 31 emptyImage.Fill(color.White) 32 } 33 34 func colorToScale(clr color.Color) (float64, float64, float64, float64) { 35 cr, cg, cb, ca := clr.RGBA() 36 if ca == 0 { 37 return 0, 0, 0, 0 38 } 39 return float64(cr) / float64(ca), float64(cg) / float64(ca), float64(cb) / float64(ca), float64(ca) / 0xffff 40 } 41 42 // DrawLine draws a line segment on the given destination dst. 43 // 44 // DrawLine is intended to be used mainly for debugging or prototyping purpose. 45 func DrawLine(dst *ebiten.Image, x1, y1, x2, y2 float64, clr color.Color) { 46 length := math.Hypot(x2-x1, y2-y1) 47 48 op := &ebiten.DrawImageOptions{} 49 op.GeoM.Scale(length, 1) 50 op.GeoM.Rotate(math.Atan2(y2-y1, x2-x1)) 51 op.GeoM.Translate(x1, y1) 52 op.ColorM.Scale(colorToScale(clr)) 53 // Filter must be 'nearest' filter (default). 54 // Linear filtering would make edges blurred. 55 dst.DrawImage(emptySubImage, op) 56 } 57 58 // DrawRect draws a rectangle on the given destination dst. 59 // 60 // DrawRect is intended to be used mainly for debugging or prototyping purpose. 61 func DrawRect(dst *ebiten.Image, x, y, width, height float64, clr color.Color) { 62 op := &ebiten.DrawImageOptions{} 63 op.GeoM.Scale(width, height) 64 op.GeoM.Translate(x, y) 65 op.ColorM.Scale(colorToScale(clr)) 66 // Filter must be 'nearest' filter (default). 67 // Linear filtering would make edges blurred. 68 dst.DrawImage(emptyImage.SubImage(image.Rect(1, 1, 2, 2)).(*ebiten.Image), op) 69 }