Skip to content

Commit 0512f30

Browse files
committed
button: Add SetImage
1 parent 0aa6fa8 commit 0512f30

File tree

5 files changed

+46
-0
lines changed

5 files changed

+46
-0
lines changed

button.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,12 @@ package gocoa
33
// #cgo CFLAGS: -x objective-c
44
// #cgo LDFLAGS: -framework Cocoa
55
// #import "button.h"
6+
// #import "image.h"
7+
// #include <stdlib.h>
68
import "C"
79
import (
810
"fmt"
11+
"image"
912
"unsafe"
1013
)
1114

@@ -147,3 +150,10 @@ func (btn *Button) OnClick(fn func()) {
147150
func (btn *Button) Remove() {
148151
C.Button_Remove(btn.buttonPtr)
149152
}
153+
154+
func (btn *Button) SetImage(img *image.RGBA) {
155+
bytes := C.CBytes(img.Pix)
156+
nsImage := C.Image_NewWithRGBA(C.int(img.Bounds().Dx()), C.int(img.Bounds().Dy()), (*C.uchar)(bytes))
157+
C.Button_SetImage(btn.buttonPtr, nsImage)
158+
C.free(bytes)
159+
}

button.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
#import "image.h"
12
#import <Cocoa/Cocoa.h>
23

34
// typedef void (*callback)(void);
@@ -25,3 +26,4 @@ void Button_SetBorderColor(ButtonPtr btnPtr, int r, int g, int b, int a);
2526
void Button_SetBorderWidth(ButtonPtr btnPtr, int borderWidth);
2627
void Button_SetState(ButtonPtr btnPtr, int state);
2728
int Button_State(ButtonPtr btnPtr);
29+
void Button_SetImage(ButtonPtr btnPtr, ImagePtr imagePtr);

button.m

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -108,3 +108,9 @@ int Button_State(ButtonPtr btnPtr) {
108108
return 3;
109109
}
110110
}
111+
112+
void Button_SetImage(ButtonPtr ptr, ImagePtr imagePtr) {
113+
NSImage *theImage = (NSImage *)imagePtr;
114+
NSButton *control = (NSButton *)ptr;
115+
[control setImage:theImage];
116+
}

image.h

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,4 @@
1+
#import <Cocoa/Cocoa.h>
2+
3+
typedef void *ImagePtr;
4+
ImagePtr Image_NewWithRGBA(int w, int h, unsigned char *rgba);

image.m

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
#import "image.h"
2+
#include "_cgo_export.h"
3+
4+
ImagePtr Image_NewWithRGBA(int w, int h, unsigned char *rgba) {
5+
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
6+
initWithBitmapDataPlanes:NULL
7+
pixelsWide:w
8+
pixelsHigh:h
9+
bitsPerSample:8
10+
samplesPerPixel:4
11+
hasAlpha:YES
12+
isPlanar:NO
13+
colorSpaceName:NSCalibratedRGBColorSpace
14+
bytesPerRow:w * 4
15+
bitsPerPixel:32];
16+
17+
unsigned char *bitmapData = [bitmap bitmapData];
18+
memcpy(bitmapData, rgba, w * h * 4);
19+
20+
NSImage *theImage = [[NSImage alloc] init];
21+
[theImage addRepresentation:bitmap];
22+
23+
return (ImagePtr)theImage;
24+
}

0 commit comments

Comments
 (0)