• Stars
    star
    121
  • Rank 293,924 (Top 6 %)
  • Language
    Swift
  • License
    MIT License
  • Created almost 9 years ago
  • Updated about 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Bitmap offscreen drawing in Swift for OS X

BitmapCanvas

Bitmap offscreen drawing in Swift for OS X

Description

A clear, simple and concise API over a CoreGraphics bitmap context.
Loosely inspired by the ImageDraw Python library.
Especially useful for easy data visualizations.

Features

  • upper-left corner based coordinates
  • pixel perfect drawing of points, lines, rectangles, ellipses and texts
  • colors as NSColor, hex strings "#AA00DF" or X11 names "SkyBlue"
  • save as PNG
  • usable with regular CoreGraphics code

Examples

let b = BitmapCanvas(32, 32, "PapayaWhip")
b[1,1] = NSColor.black

b[1,3] = "red" b[2,3] = "#00FF00" b[3,3] = NSColor.blue

b.line(P(1,1), P(10,10))

b.line(P(1,10), P(10,19), "red") b.lineHorizontal(P(1,21), width:20) b.lineVertical(P(20, 1), height:19, "blue")

b.rectangle(R(5,5,20,10))

b.rectangle(R(10,10,20,10), stroke:"blue", fill:"magenta")

b.ellipse(R(5,5,20,10))

b.ellipse(R(10,10,18,21), stroke:"blue", fill:"magenta")

let b = BitmapCanvas(32, 32, "PapayaWhip")

b.line(P(10,0), P(25,31), "red")

b.ellipse(R(15,10,15,15))

b.fill(P(30,1), color:"yellow")

b.text("hi", P(5,10))

b.text("hello", P(20,30), rotationDegrees: -90, font: NSFont(name: "Helvetica", size: 10)!, color: NSColor.red)

b.image(fromPath:"/usr/share/httpd/icons/sphere2.png", P(0,0))
let b = BitmapCanvas(32, 32, "PapayaWhip")

b.setAllowsAntialiasing(true)

let points = [P(3,3), P(28,5), P(25,22), P(12,18)]

b.polygon(points, stroke:"blue", fill:"SkyBlue")

b.save("/tmp/polygon.png", open:true)

b.setAllowsAntialiasing(true)

NSColor.orangeColor().setFill()

let bp = NSBezierPath() bp.moveToPoint(P(2,2)) bp.curveToPoint(P(20,14), controlPoint1: P(14,30), controlPoint2: P(15,30)) bp.curveToPoint(P(32,13), controlPoint1: P(24,14), controlPoint2: P(24,19)) bp.closePath() bp.fill() bp.stroke()

let b = BitmapCanvas(32, 32, "PapayaWhip")
let c = b.cgContext

c.addEllipse(in: R(2, 2, 24, 24)) c.strokePath()

b.setAllowsAntialiasing(true)

c.setStrokeColor(NSColor.blue.cgColor) c.addEllipse(in: R(12, 12, 24, 24)) c.strokePath()

b.save("/tmp/cgcontext.png")

b.save("/tmp/image.png", open:true)

You can also dump the X11 color list with:

X11Colors.dump("/opt/X11/share/X11/rgb.txt", outPath:"/tmp/X11.clr")

or download the file directly X11.clr.zip

X11 Color List

Other images with sample code:

gradient

let (w, h) = (255, 255)

let b = BitmapCanvas(w, h)
for i in 0..<w {
    for j in 0..<h {
        b[i,j] = NSColor(i,j,100)
    }
}

b.save("/tmp/gradient.png")

voronoi

let w = 255
let h = 255
let n = 25

let b = BitmapCanvas(w, h)

var pointsColors : [(NSPoint, NSColor)] = []

for _ in 0...n {
    let p = RandomPoint(maxX: w, maxY: h)
    let c = NSColor.randomColor
    pointsColors.append((p,c))
}

for x in 0...w-1 {
    for y in 0...h-1 {
        let distances = pointsColors.map { hypot($0.0.x - x, $0.0.y - y) }
        b[x,y] = pointsColors[distances.indexOf(distances.minElement()!)!].1
    }
}

for (p,_) in pointsColors {
    let rect = R(p.x-1, p.y-1, 3, 3)
    b.ellipse(rect, stroke:"black", fill:"black")
}

b.save("/tmp/voronoi.png")

Other pictures with source code in the project:

Swift implementation of Nadieh Bremer's work "Exploring the Art hidden in Pi".

pi walk

"Schotter" by Georg Nees where the idea is that randomness for x, y and rotation does increase at each row. Also created a rainbow-colored version.

schotter schotter color

rainbow fall

More Repositories

1

iOS-Runtime-Headers

iOS Objective-C headers as derived from runtime introspection
Objective-C
7,919
star
2

RuntimeBrowser

Objective-C Runtime Browser, for Mac OS X and iOS
Objective-C
3,507
star
3

objc_dep

Graph the import dependancies in an Objective-C project
Python
1,343
star
4

STTwitter

A stable, mature and comprehensive Objective-C library for Twitter REST API 1.1
Objective-C
1,000
star
5

STHTTPRequest

Obj-C / Cocoa HTTP requests for humans
Objective-C
827
star
6

JSONTestSuite

A comprehensive test suite for RFC 8259 compliant JSON parsers
C++
826
star
7

objc_cover

Quick Python script over otool to help spotting potentially unused methods in Objective-C Mach-O executable files
Python
448
star
8

SpyPhone

This project shows the kind of data a rogue iPhone application can collect.
Objective-C
310
star
9

objc_strings

Helps in localizing Cocoa applications by showing unused/missing keys in Localizable.strings.
Python
191
star
10

BatteryChart

Drawing iPhone Battery Charge / Discharge
C
102
star
11

gmap_tiles

Download and merge Google Maps tiles
Python
96
star
12

UniBinary

Encodes data into printable Unicode characters.
JavaScript
90
star
13

nsarray-functional

Objective-C category to add Python-like map, filter and reduce methods to Cocoa NSArray.
Objective-C
83
star
14

ScreenTime

create movies from periodic screenshots
Swift
74
star
15

MobileSignal

Map and chart the signal type and strength on your iOS device
Objective-C
69
star
16

STJSON

A JSON Parser in Swift 3 compliant with RFC 7159
Swift
68
star
17

BinUtils

Swift functions to ease working with binary formats
Swift
68
star
18

SQRiskCursor

Custom UIControl using CoreAnimation
Objective-C
59
star
19

CocoaSlideShow

Simple Image Browser for Mac OS X
Objective-C
52
star
20

SEVerticalTabBar

A vertical tab bar implementation for iPad
41
star
21

UTIsExplorer

Find OS X UTIs, build up the inheritance tree, save it as a Graphviz graph.
Objective-C
40
star
22

bfps

A Brainfuck interpreter written in PostScript
PostScript
35
star
23

ShapefileReader

A shapefile reader in Swift
Swift
34
star
24

FSWalker

A File System Browser for iOS
Objective-C
30
star
25

iCalReport

iCalReport reads iCal events and reports the time you spend on projects.
Python
25
star
26

UnicodePoster

Unicode Poster
Objective-C
25
star
27

CrashReports

Symbolicate iOS crash reports
Perl
23
star
28

filters

Apply filters on iOS Camera.app JPG files imported with Image Capture.
Python
21
star
29

osx_frameworks

Generate a .dot file of OS X frameworks dependencies
Python
21
star
30

Quickies

Simple PHP/MySQL application to share notes organized by category.
PHP
19
star
31

TwitHunter

Cocoa Twitter client with scoring
Objective-C
18
star
32

Brainfuck

A flexible Brainfuck / Brainloller / Braincopter interpreter in Swift 3.1.
Swift
15
star
33

Wireworld

A simple Wireworld cellular automaton explorer in Swift
Swift
13
star
34

draw_bytes

draw any file as a picture
Python
13
star
35

PulsarRuns

Pulsar-plot of Strava runs in Swift 3
Swift
12
star
36

DevTeamActivity

Generates a picture summarising the activity of a dev team on one or several repositories
Swift
11
star
37

Home-Made-Maps

Home Made Maps
11
star
38

SwissSMS

Mac OS X SMS sender
Objective-C
11
star
39

ECAExplorer

A simple and interactive tool to explore Elementary Cellular Automata, in Swift
Swift
10
star
40

Intertwined

Draw intertwined threads, knots and knitting figures with PyCairo
Python
9
star
41

EasterEggs

A social game that consists in catching QR-codes
Python
9
star
42

efx-backtest

Simple tool to backtest eForex strategies
Python
9
star
43

SwiftDrawing

Drawing in Swift
Swift
9
star
44

STMovingImages

Create .MOV and .GIF from NSImages in Swift 3
Swift
8
star
45

Twitter-Saver

Save your Twitter statuses in CSV format.
Python
7
star
46

deprecated-fb_albums

Download photos from Facebook photo albums.
Python
6
star
47

Isometric

Isometric screensaver for macOS, written in Swift
Swift
6
star
48

PyCairoVisualDoc

Turns PyCairo snippets into HTML
Python
6
star
49

AntennasAssignment

A combinatorial optimisation problem
Objective-C
5
star
50

HTTPRequests

NSURLRequest extensions in Swift
Swift
4
star
51

pmlogs_to_ical

Create a calendar of wake-sleep sessions based on power management logs.
4
star
52

JavaDoc

Legacy OS X Dashboard widget to access Java documentation
Objective-C
3
star
53

IsoRenderer

A 2D isometric renderer in Python 3 based on PyCairo
Python
3
star
54

Boggle

Python
2
star
55

WangTilesTuringMachines

Simulating Wang Tiles with Turing Machines
Python
2
star
56

matplotlib_experiments

Matplotlib experiments
2
star
57

MNIST

Measuring the accuracy of a trivial approach to the MNIST digits classification problem
Python
2
star
58

newsmemory

Django web application to crawl, store and browse pieces of news
Python
2
star
59

AVS

encrypt / decrypt Swiss AVS IDs
Python
1
star
60

HEIG-VD

A few projects from my time at Engineering School HEIG-VD
C
1
star
61

phpMyFlatSite

Minimal framework to run a classic, single user, dynamic web site.
PHP
1
star
62

Mowgli

Generate a static website from Markdown files with <150 lines of Python
CSS
1
star
63

PyGame

Experiments with PyGame
Python
1
star
64

STStrava

Experimental visualisation of runs using Swift and Strava API
Swift
1
star