# 蝈蝈俊的技术心得

posts - 490, comments - 173, trackbacks - 0, articles - 0

### 公告

   1: // Draw calls DrawMask with a nil mask.
   2: func Draw(dst Image, r image.Rectangle, src image.Image, sp image.Point, op Op)
   3: func DrawMask(dst Image, r image.Rectangle, src image.Image, sp image.Point,
   4:     mask image.Image, mp image.Point, op Op)

# 给一个矩形填充颜色

   1: m := image.NewRGBA(image.Rect(0, 0, 640, 480))
   2: blue := color.RGBA{0, 0, 255, 255}
   3: draw.Draw(m, m.Bounds(), &image.Uniform{blue}, image.ZP, draw.Src)

# 拷贝图片的一部分

   1: r := image.Rectangle{dp, dp.Add(sr.Size())}  // 获得更换区域
   2: draw.Draw(dst, r, src, sr.Min, draw.Src)

   1: sr = src.Bounds()         // 获取要复制图片的尺寸
   2: r := sr.Sub(sr.Min).Add(dp)   // 目标图的要剪切区域
   3: draw.Draw(dst, r, src, sr.Min, draw.Src)

# 图片滚动效果

   1: b := m.Bounds()
   2: p := image.Pt(0, 20)
   3: // Note that even though the second argument is b,
   4: // the effective rectangle is smaller due to clipping.
   5: draw.Draw(m, b, m, b.Min.Add(p), draw.Src)
   6: dirtyRect := b.Intersect(image.Rect(b.Min.X, b.Max.Y-20, b.Max.X, b.Max.Y))

# 把一个图片转成RGBA格式

   1: b := src.Bounds()
   2: m := image.NewRGBA(b)
   3: draw.Draw(m, b, src, b.Min, draw.Src)

# 通过蒙版画特效

   1: type circle struct {
   2:     p image.Point
   3:     r int
   4: }
   5:
   6: func (c *circle) ColorModel() color.Model {
   7:     return color.AlphaModel
   8: }
   9:
  10: func (c *circle) Bounds() image.Rectangle {
  11:     return image.Rect(c.p.X-c.r, c.p.Y-c.r, c.p.X+c.r, c.p.Y+c.r)
  12: }
  13:
  14: func (c *circle) At(x, y int) color.Color {
  15:     xx, yy, rr := float64(x-c.p.X)+0.5, float64(y-c.p.Y)+0.5, float64(c.r)
  16:     if xx*xx+yy*yy < rr*rr {
  17:         return color.Alpha{255}
  18:     }
  19:     return color.Alpha{0}
  20: }
  21:
  22:
  23: draw.DrawMask(dst, dst.Bounds(), src, image.ZP, &circle{p, r}, image.ZP, draw.Over)

   1: type Image interface {
   2:     // ColorModel returns the Image's color model.
   3:     ColorModel() color.Model
   4:     // Bounds returns the domain for which At can return non-zero color.
   5:     // The bounds do not necessarily contain the point (0, 0).
   6:     Bounds() Rectangle
   7:     // At returns the color of the pixel at (x, y).
   8:     // At(Bounds().Min.X, Bounds().Min.Y) returns the upper-left pixel of the grid.
   9:     // At(Bounds().Max.X-1, Bounds().Max.Y-1) returns the lower-right one.
  10:     At(x, y int) color.Color
  11: }

# 画一个字体

   1: src := &image.Uniform{color.RGBA{0, 0, 255, 255}}
   2: mask := theGlyphImageForAFont()
   3: mr := theBoundsFor(glyphIndex)
   4: draw.DrawMask(dst, mr.Sub(mr.Min).Add(p), src, image.ZP, mask, mr.Min, draw.Over)

http://golang.org/doc/progs/image_draw.go