Skip to content

Instantly share code, notes, and snippets.

@menangen
Created March 5, 2017 13:26
Show Gist options
  • Save menangen/168f4d1a1bc3136c7a527ae909cc8e91 to your computer and use it in GitHub Desktop.
Save menangen/168f4d1a1bc3136c7a527ae909cc8e91 to your computer and use it in GitHub Desktop.
Swift Perlin Noise iOS
import UIKit
import GameKit
class View: UIView {
let square_side = 5
let height_pixels = 115
let width_pixels = 80
override func draw(_ rect: CGRect) {
// Drawing code
let context = UIGraphicsGetCurrentContext()!
//let source: GKPerlinNoiseSource = GKPerlinNoiseSource(frequency: 10.0, octaveCount: 4, persistence: 0.5, lacunarity: 2.145, seed: 2)
let source: GKRidgedNoiseSource = GKRidgedNoiseSource(frequency: 1.0, octaveCount: 4, lacunarity: 2.0, seed: 2)
let noise: GKNoise = GKNoise(source)
let map: GKNoiseMap = GKNoiseMap(noise, size: vector_double2(3.0, 3.0), origin: vector_double2(0, 0),
sampleCount: vector_int2(Int32(width_pixels), Int32(height_pixels)), seamless: false)
for coord_y in 0..<height_pixels {
for coord_x in 0..<width_pixels {
let vector: vector_int2 = vector_int2(Int32(coord_x), Int32(coord_y))
let result = map.value(at: vector)
var color: CGFloat = CGFloat(result * 0.5 + 0.5)
if color < 0.0 { color = 0.0 }
else if color > 1.0 { color = 1.0 }
context.setFillColor(
red: 1.0,
green: 1.0,
blue: 1.0,
alpha: color);
context.addRect(
CGRect(x: square_side * coord_x,
y: square_side * coord_y,
width: square_side,
height: square_side)
)
context.fillPath();
}
}
}
}
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let view : UIView = View()
self.view = view;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment