Adding custom icons for MacOS in Xojo
So today we want to show you how to add a custom icon to a file with three sample snippets. First with an existing picture, second with creating a picture with alpha channel and third one with a masked image. Depending on what you do, all ways work, but if you have an image already or just compose one for the new file, one way may be better suitable.
First, with an existing picture in the project or a variable:
// write a file
dim f as FolderItem = SpecialFolder.Desktop.Child("test.txt")
dim t as TextOutputStream = TextOutputStream.Create(f)
t.WriteLine "Hello"
t.Close
// use existing picture
dim g as new NSImageMBS(SomePicture)
dim b as Boolean = NSWorkspaceMBS.setIcon(g, f, 0)
if not b then
MsgBox "Failed to add icon"
end if
Second, with alpha picture:
// write a file
dim f as FolderItem = SpecialFolder.Desktop.Child("test.txt")
dim t as TextOutputStream = TextOutputStream.Create(f)
t.WriteLine "Hello"
t.Close
// create picture for icon with alpha
dim p as new Picture(512, 512)
dim pg as Graphics = p.Graphics
pg.ForeColor = rgb(255,0,0)
pg.FillOval 0,0,p.Width,p.Height
// add icon
dim g as new NSImageMBS(p)
dim b as Boolean = NSWorkspaceMBS.setIcon(g, f, 0)
if not b then
MsgBox "Failed to add icon"
end if
Third, with masked picture:// write a file
dim f as FolderItem = SpecialFolder.Desktop.Child("test.txt")
dim t as TextOutputStream = TextOutputStream.Create(f)
t.WriteLine "Hello"
t.Close
// create picture for icon
dim p as new Picture(512, 512, 32)
p.Graphics.ForeColor = rgb(0,0,0)
p.Graphics.FillRect 0,0,p.Width,p.Height
p.Graphics.ForeColor = rgb(255,0,0)
p.Graphics.FillOval 0,0,p.Width,p.Height
// add mask
dim m as Picture = p.mask
m.Graphics.ForeColor = &cFFFFFF // first all white
m.Graphics.FillRect 0, 0, p.Width, p.Height
m.Graphics.ForeColor = &c000000 // visible parts black
m.Graphics.FillOval 0, 0, p.Width, p.Height
// add icon
dim g as new NSImageMBS(p)
dim b as Boolean = NSWorkspaceMBS.setIcon(g, f, 0)
if not b then
MsgBox "Failed to add icon"
end if
We hope those snippets help you and if you have questions, please do not hesitate to contact us.PS: The Xojo project icon made with our QuickLook extension.