Skip to content

Instantly share code, notes, and snippets.

@trilliwon
trilliwon / uiimage-data.swift
Last active January 12, 2024 14:45
Swift UIImage to Data, Data to UIImage
// Swift4
let image = UIImage(named: "sample")
let data = image?.pngData()
let data = image?.jpegData(compressionQuality: 0.9)
let uiImage: UIImage = UIImage(data: imageData)
// deprecated
// var imageData: Data = UIImagePNGRepresentation(image)
@MrJackdaw
MrJackdaw / UIView+Border.swift
Last active May 12, 2023 19:02
Swift 3 Extension for adding border to one side of UIView
// This syntax reflects changes made to the Swift language as of Aug. '16
extension UIView {
// Example use: myView.addBorder(toSide: .Left, withColor: UIColor.redColor().CGColor, andThickness: 1.0)
enum ViewSide {
case Left, Right, Top, Bottom
}
@soggybag
soggybag / ViewController.swift
Created February 23, 2016 19:04
Sine Wave with fill using UIBezierPath
// Draw a sine curve with a fill
let centerY = frame.height / 2 // find the vertical center
let steps = 200 // Divide the curve into steps
let stepX = frame.width / CGFloat(steps) // find the horizontal step distance
// Make a path
let path = UIBezierPath()
// Start in the lower left corner
path.moveToPoint(CGPoint(x: 0, y: frame.height))
@FreyaHolmer
FreyaHolmer / RigidbodyMassCalculator.cs
Created December 18, 2015 19:54
Used to approximate a proper mass value for all the colliders in a given Rigidbody
using UnityEngine;
using System.Linq;
[RequireComponent(typeof(Rigidbody))]
public class RigidbodyMassCalculator : MonoBehaviour {
public float density = 1f;
public bool recalculateOnAwake = true;
Rigidbody rb;
@Rathgore
Rathgore / gist:dd873a88dc6866666c5a
Created November 25, 2014 00:55
CRC-CCITT NSData extension in Swift
import Foundation
let SEED: UInt16 = 0xFFFF
let crcCCITTLookupTable: [UInt16] = [
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50A5, 0x60C6, 0x70E7, 0x8108,
0x9129, 0xA14A, 0xB16B, 0xC18C, 0xD1AD, 0xE1CE, 0xF1EF, 0x1231, 0x0210,
0x3273, 0x2252, 0x52B5, 0x4294, 0x72F7, 0x62D6, 0x9339, 0x8318, 0xB37B,
0xA35A, 0xD3BD, 0xC39C, 0xF3FF, 0xE3DE, 0x2462, 0x3443, 0x0420, 0x1401,
0x64E6, 0x74C7, 0x44A4, 0x5485, 0xA56A, 0xB54B, 0x8528, 0x9509, 0xE5EE,
func encode<T>(var value: T) -> NSData {
return withUnsafePointer(&value) { p in
NSData(bytes: p, length: sizeofValue(value))
}
}
func decode<T>(data: NSData) -> T {
let pointer = UnsafeMutablePointer<T>.alloc(sizeof(T.Type))
data.getBytes(pointer)