Reputation: 23
Change the value of NSSlider and repeat setting the opacity of NSImage using the
public extension NSImage {
func withAlpha(_ alpha: CGFloat) -> NSImage {
guard alpha >= 0.0 && alpha <= 1.0 else { return self }
let newImage = NSImage(size: size)
newImage.lockFocus()
let rect = NSRect(origin: .zero, size: size)
draw(in: rect, from: rect, operation: .sourceOver, fraction: alpha)
newImage.unlockFocus()
return newImage
}
func averageAlpha(sampleRate: Int = 10) -> CGFloat? {
guard sampleRate > 0 else { return nil }
guard let tiffData = self.tiffRepresentation,
let bitmapImageRep = NSBitmapImageRep(data: tiffData)
else { return nil }
let width = bitmapImageRep.pixelsWide
let height = bitmapImageRep.pixelsHigh
var totalAlpha: CGFloat = 0.0
var pixelCount: Int = 0
for x in stride(from: 0, to: width, by: sampleRate) {
for y in stride(from: 0, to: height, by: sampleRate) {
if let color = bitmapImageRep.colorAt(x: x, y: y) {
totalAlpha += color.alphaComponent
pixelCount += 1
}
}
}
return pixelCount > 0 ? totalAlpha / CGFloat(pixelCount) : nil
}
}
let originalImage = imageView.image
let oneImage = originalImage.withAlpha(0.3)
let twoImage = originalImage.withAlpha(0.8)
let value = twoImage.averageAlpha()
What should I do in the withAlpha(_ :) method so that the value is 0.8
Upvotes: 0
Views: 21