Swift Swift - 8 months ago 67
Swift Question

How to adjust brightness with NSSlider for NSImage class via Swift?

I need to control a transparency (opacity) of my uploaded images (JPEG, PNG, TIFF...) with NSSlider. How I can do it?
Here is a code written in AppDelegate.swift

@IBAction func importButton(sender: AnyObject) {

let uploadFile: NSOpenPanel = NSOpenPanel()

uploadFile.allowsMultipleSelection = false
uploadFile.canChooseFiles = true
uploadFile.canChooseDirectories = false

let chosenPicture = uploadFile.URL
if(chosenPicture != nil) {

let pictureImport = NSImage(contentsOfURL: chosenPicture!)
imageWell.image = pictureImport

@IBAction func brightnessSlider(sender: AnyObject) {

var brightnessValue: Int = 100



Try this

@IBAction func brightnessSlider(sender: NSSlider) {

    var alpha = sender.minValue + (sender.doubleValue-sender.minValue)/(sender.maxValue-sender.minValue)
    imageWell.alphaValue = CGFloat(alpha)


Calculation for alpha becomes simpler if your minValue is always 0:

var alpha = sender.doubleValue/sender.maxValue