examples/highdpi: Async loading

This commit is contained in:
Hajime Hoshi 2018-01-29 23:04:11 +09:00
parent 2322c5600b
commit 19f7f44f1c

View File

@ -28,8 +28,9 @@ import (
) )
var ( var (
count int count int
highDPIImage *ebiten.Image highDPIImage *ebiten.Image
highDPIImageCh = make(chan *ebiten.Image)
) )
func init() { func init() {
@ -37,28 +38,48 @@ func init() {
// https://commons.wikimedia.org/wiki/File:As08-16-2593.jpg // https://commons.wikimedia.org/wiki/File:As08-16-2593.jpg
const url = "https://upload.wikimedia.org/wikipedia/commons/1/1f/As08-16-2593.jpg" const url = "https://upload.wikimedia.org/wikipedia/commons/1/1f/As08-16-2593.jpg"
res, err := http.Get(url) // Load the image asynchronously.
if err != nil { go func() {
log.Fatal(err) res, err := http.Get(url)
} if err != nil {
defer res.Body.Close() log.Fatal(err)
}
defer res.Body.Close()
img, _, err := image.Decode(res.Body) img, _, err := image.Decode(res.Body)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
highDPIImage, err = ebiten.NewImageFromImage(img, ebiten.FilterLinear) eimg, err := ebiten.NewImageFromImage(img, ebiten.FilterLinear)
if err != nil { if err != nil {
log.Fatal(err) log.Fatal(err)
} }
highDPIImageCh <- eimg
close(highDPIImageCh)
}()
} }
func update(screen *ebiten.Image) error { func update(screen *ebiten.Image) error {
if highDPIImage == nil {
// Use select and 'default' clause for non-blocking receiving.
select {
case img := <-highDPIImageCh:
highDPIImage = img
default:
}
}
if ebiten.IsRunningSlowly() { if ebiten.IsRunningSlowly() {
return nil return nil
} }
if highDPIImage == nil {
ebitenutil.DebugPrint(screen, "Loading the image...")
return nil
}
scale := ebiten.DeviceScaleFactor() scale := ebiten.DeviceScaleFactor()
sw, sh := screen.Size() sw, sh := screen.Size()