Nothing Special   »   [go: up one dir, main page]

Skip to content

Commit

Permalink
button: Add SetImage
Browse files Browse the repository at this point in the history
  • Loading branch information
roblillack committed May 27, 2024
1 parent 0aa6fa8 commit 0512f30
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 0 deletions.
10 changes: 10 additions & 0 deletions button.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,12 @@ package gocoa
// #cgo CFLAGS: -x objective-c
// #cgo LDFLAGS: -framework Cocoa
// #import "button.h"
// #import "image.h"
// #include <stdlib.h>
import "C"
import (
"fmt"
"image"
"unsafe"
)

Expand Down Expand Up @@ -147,3 +150,10 @@ func (btn *Button) OnClick(fn func()) {
func (btn *Button) Remove() {
C.Button_Remove(btn.buttonPtr)
}

func (btn *Button) SetImage(img *image.RGBA) {
bytes := C.CBytes(img.Pix)
nsImage := C.Image_NewWithRGBA(C.int(img.Bounds().Dx()), C.int(img.Bounds().Dy()), (*C.uchar)(bytes))
C.Button_SetImage(btn.buttonPtr, nsImage)
C.free(bytes)
}
2 changes: 2 additions & 0 deletions button.h
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
#import "image.h"
#import <Cocoa/Cocoa.h>

// typedef void (*callback)(void);
Expand Down Expand Up @@ -25,3 +26,4 @@ void Button_SetBorderColor(ButtonPtr btnPtr, int r, int g, int b, int a);
void Button_SetBorderWidth(ButtonPtr btnPtr, int borderWidth);
void Button_SetState(ButtonPtr btnPtr, int state);
int Button_State(ButtonPtr btnPtr);
void Button_SetImage(ButtonPtr btnPtr, ImagePtr imagePtr);
6 changes: 6 additions & 0 deletions button.m
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,9 @@ int Button_State(ButtonPtr btnPtr) {
return 3;
}
}

void Button_SetImage(ButtonPtr ptr, ImagePtr imagePtr) {
NSImage *theImage = (NSImage *)imagePtr;
NSButton *control = (NSButton *)ptr;
[control setImage:theImage];
}
4 changes: 4 additions & 0 deletions image.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
#import <Cocoa/Cocoa.h>

typedef void *ImagePtr;
ImagePtr Image_NewWithRGBA(int w, int h, unsigned char *rgba);
24 changes: 24 additions & 0 deletions image.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#import "image.h"
#include "_cgo_export.h"

ImagePtr Image_NewWithRGBA(int w, int h, unsigned char *rgba) {
NSBitmapImageRep *bitmap = [[NSBitmapImageRep alloc]
initWithBitmapDataPlanes:NULL
pixelsWide:w
pixelsHigh:h
bitsPerSample:8
samplesPerPixel:4
hasAlpha:YES
isPlanar:NO
colorSpaceName:NSCalibratedRGBColorSpace
bytesPerRow:w * 4
bitsPerPixel:32];

unsigned char *bitmapData = [bitmap bitmapData];
memcpy(bitmapData, rgba, w * h * 4);

NSImage *theImage = [[NSImage alloc] init];
[theImage addRepresentation:bitmap];

return (ImagePtr)theImage;
}

0 comments on commit 0512f30

Please sign in to comment.