0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【A Tour of Go】Methods and interfaces/Exercise: Images (25/26)

Posted at

A Tour of Go の Exercise を実施したときのメモ。

  • 「自分の Image 型を定義し、 インタフェースを満たすのに必要なメソッド を実装し、〜」のインターフェイス
type Image interface {
        // ColorModel returns the Image's color model.
        ColorModel() color.Model
        // Bounds returns the domain for which At can return non-zero color.
        // The bounds do not necessarily contain the point (0, 0).
        Bounds() Rectangle
        // At returns the color of the pixel at (x, y).
        // At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid.
        // At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one.
        At(x, y int) color.Color
}
  • 問題に記載してあるとおりに実装する(以下、問題から引用)
    • Bounds は、 image.Rect(0, 0, w, h) のようにして image.Rectangle を返すようにします。
      • →ここのwhImage{}で指定した値になるので、type Imagew, h intを追加
    • ColorModel は、 color.RGBAModel を返すようにします。
      • →これは、ほんとにそのまま。
    • At は、ひとつの色を返します。 生成する画像の色の値 v を color.RGBA{v, v, 255, 255} を利用して返すようにします。
      • →これもほぼそのままだが、vの定義(uint8(x * y))が必要。
exercise-images.go
package main

import "golang.org/x/tour/pic"
import (
	"image"
	"image/color"
)

type Image struct{
	w, h int
}

func (img Image) ColorModel() color.Model {
	return color.RGBAModel
}
func (img Image) Bounds() image.Rectangle {
	return image.Rect(0,0,img.w,img.h)
}
func (img Image) At(x, y int) color.Color {
	v := uint8(x * y)
	return color.RGBA{v, v, 255, 255}
}

func main() {
	m := Image{100, 100}
	pic.ShowImage(m)
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?