Skip to content

Instantly share code, notes, and snippets.

View garethng's full-sized avatar
🌏
Focusing

Gareth Ng garethng

🌏
Focusing
View GitHub Profile
@garethng
garethng / calculateStringHeightAndWidth.swift
Created September 29, 2022 02:35
Extension String to calculate the width and height of a label based on the string length
extension String {
func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
return ceil(boundingBox.height)
}
func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
@garethng
garethng / roundCorner.swift
Created August 12, 2022 08:48
set roundCorner for UIView (select the corners)
extension UIView {
func roundCorners(corners: UIRectCorner, radius: CGFloat) {
let path = UIBezierPath(roundedRect: bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
layer.mask = mask
}
}
@garethng
garethng / label2image.swift
Created April 13, 2021 09:13
convert label to icon
public extension NSView {
var image: NSImage? {
guard let bitmapImageRep = bitmapImageRepForCachingDisplay(in: bounds) else { return nil }
cacheDisplay(in: bounds, to: bitmapImageRep)
guard let cgImage = bitmapImageRep.cgImage else { return nil }
return NSImage(cgImage: cgImage, size: bounds.size)
}
}
@garethng
garethng / radixSort.go
Last active November 26, 2020 10:01
radixSort golang 基数排序
func radixSort(nums []int) []int{
maxValue := maxValueOfList(nums...)
a := 1
for k:=0;a<=maxValue;k++{
buckets := map[int][]int{}
for i:=0;i<10;i++{
buckets[i] = []int{}
}
for _,num := range nums{
@garethng
garethng / synchronized.swift
Created July 7, 2020 12:52
swift @synchronuzed
@discardableResult
public func synchronized<T>(_ lock: AnyObject, closure:() -> T) -> T {
objc_sync_enter(lock)
defer { objc_sync_exit(lock) }
return closure()
}
@garethng
garethng / progress.py
Created May 7, 2020 02:56
python progress
def progress(percent,width=50):
if percent >= 100:
percent=100
show_str=('[%%-%ds]' %width) %(int(width * percent/100)*"#")
print('\r%s %d%%' %(show_str,percent),end='')