/
icon.go
110 lines (91 loc) · 2.49 KB
/
icon.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
// Copyright 2011 The Walk Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package walk
import (
"image"
"path/filepath"
"syscall"
)
import . "github.com/lxn/go-winapi"
// Icon is a bitmap that supports transparency and combining multiple
// variants of an image in different resolutions.
type Icon struct {
hIcon HICON
}
// NewIconFromFile returns a new Icon, using the specified icon image file.
func NewIconFromFile(filePath string) (*Icon, error) {
absFilePath, err := filepath.Abs(filePath)
if err != nil {
return nil, wrapError(err)
}
hIcon := HICON(LoadImage(
0,
syscall.StringToUTF16Ptr(absFilePath),
IMAGE_ICON,
0,
0,
LR_DEFAULTSIZE|LR_LOADFROMFILE))
if hIcon == 0 {
return nil, lastError("LoadImage")
}
return &Icon{hIcon: hIcon}, nil
}
// NewIconFromResource returns a new Icon, using the specified icon resource.
func NewIconFromResource(resName string) (ic *Icon, err error) {
hInst := GetModuleHandle(nil)
if hInst == 0 {
err = lastError("GetModuleHandle")
return
}
if hIcon := LoadIcon(hInst, syscall.StringToUTF16Ptr(resName)); hIcon == 0 {
err = lastError("LoadIcon")
} else {
ic = &Icon{hIcon: hIcon}
}
return
}
func NewIconFromImage(im image.Image) (ic *Icon, err error) {
hIcon, err := createAlphaCursorOrIconFromImage(im, image.Pt(0, 0), true)
if err != nil {
return nil, err
}
return &Icon{hIcon}, nil
}
// Dispose releases the operating system resources associated with the Icon.
func (i *Icon) Dispose() error {
if i.hIcon == 0 {
return nil
}
if !DestroyIcon(i.hIcon) {
return lastError("DestroyIcon")
}
i.hIcon = 0
return nil
}
// create an Alpha Icon or Cursor from an Image
// http://support.microsoft.com/kb/318876
func createAlphaCursorOrIconFromImage(im image.Image, hotspot image.Point, fIcon bool) (HICON, error) {
hBitmap, err := hBitmapFromImage(im)
if err != nil {
return 0, err
}
defer DeleteObject(HGDIOBJ(hBitmap))
// Create an empty mask bitmap.
hMonoBitmap := CreateBitmap(int32(im.Bounds().Dx()), int32(im.Bounds().Dy()), 1, 1, nil)
if hMonoBitmap == 0 {
return 0, newError("CreateBitmap failed")
}
defer DeleteObject(HGDIOBJ(hMonoBitmap))
var ii ICONINFO
if fIcon {
ii.FIcon = TRUE
}
ii.XHotspot = uint32(hotspot.X)
ii.YHotspot = uint32(hotspot.Y)
ii.HbmMask = hMonoBitmap
ii.HbmColor = hBitmap
// Create the alpha cursor with the alpha DIB section.
hIconOrCursor := CreateIconIndirect(&ii)
return hIconOrCursor, nil
}