- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我试图在 Swift 中获取 UIImage 的主要颜色,并尝试移植 this code .不幸的是,代码一直返回相同的颜色。我看到了the answer provided here也不断返回相同的颜色。我避免使用 CIFilter,因为它只返回我研究中的平均颜色。
在移植的代码下方。我已将 CGContext 数据设置为 nil,因为 Swift 可以处理它的内存,并且在我的测试中它给出了很多内存错误。
func mainColors(image:UIImage, detail: Int) -> [UIColor] {
//COLOR PROCESS STEP 1:
//Determine the detail.
var dimension = 10
var flexibility = 2
var range = 60
//Low detail.
if detail == 0 {
dimension = 4
flexibility = 1
range = 100
}
//High detail.
else if detail == 2 {
dimension = 100
flexibility = 10
range = 20
}
//COLOR PROCESS STEP 2:
//Determine the colors in the image.
//Create an array to store the colors.
var colors = Array<Array<CGFloat>>()
//Get the bitmap data of the image.
let imageRef = image.cgImage
//Variable to store the color space, RGB in this case.
let colorSpace = CGColorSpaceCreateDeviceRGB()
//Additional CGContext data.
let bytesPerPixel = 4
let bytesPerRow = bytesPerPixel * dimension
let bitsPerComponent = 8
//Create the context. Data uses the memory pointer created above, the width and height determine the dimensions of the bitmap, the space is for the colorspace, the bitmap specifies the alpha channel.
let context = CGContext(data: nil, width: dimension, height: dimension, bitsPerComponent: bitsPerComponent, bytesPerRow: bytesPerRow, space: colorSpace, bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue | CGBitmapInfo.byteOrder32Big.rawValue)!
//Draw the image.
let rect = CGRect(x: 0, y: 0, width: dimension, height: dimension)
context.draw(imageRef!, in: rect)
//Iterate through the raw data in order to create a UIColor.
var x = 0
var y = 0
for _ in 0..<(dimension * dimension) {
let index = (bytesPerRow * y) + x * bytesPerPixel
let red = CGFloat(index)
let green = CGFloat(index + 1)
let blue = CGFloat(index + 2)
let alpha = CGFloat(index + 3)
let color = [red, green, blue, alpha]
colors.append(color)
y += 1
if y == dimension {
y = 0
x += 1
}
}
//Deallocate the mutable pointer.
//free(rawData)
//COLOR PROCESS STEP 3:
//Add some color flexibility.
//Create an array containing the previous colored items and create another one for the flexible colors.
var copiedColors = colors
var flexibleColors = Array<String>()
//Iterate through the copied colors in order to create an improved UIColor.
let flexFactor = flexibility * 2 + 1
let factor = flexFactor * flexFactor * 3
for n in 0..<(dimension * dimension) {
let pixelColors = copiedColors[n]
var reds = Array<CGFloat>()
var greens = Array<CGFloat>()
var blues = Array<CGFloat>()
for p in 0..<3 {
let rgb = pixelColors[p]
for f in -flexibility...flexibility {
var newRGB = rgb + CGFloat(f)
if newRGB < 0 {
newRGB = 0
}
switch p {
case 0:
reds.append(newRGB)
case 1:
greens.append(newRGB)
case 2:
blues.append(newRGB)
default:
print("Error! Loop out of range! \(p)")
}
}
}
var r = 0
var g = 0
var b = 0
for _ in 0..<factor {
let red = reds[r]
let green = greens[g]
let blue = blues[b]
let rgbString = "\(red),\(green),\(blue)"
flexibleColors.append(rgbString)
b += 1
if b == flexFactor {
b = 0
g += 1
}
if g == flexFactor {
g = 0
r += 1
}
}
}
//COLOR PROCESS STEP 4:
//Distinguish the colors. Orders the flexible colors by their occurence and then keeps them if they are sufficiently disimilar.
//Dictionary to store all the colors.
let colorCounter = NSMutableDictionary()
//Check the number of times item is in array.
let countedSet = NSCountedSet(array: flexibleColors)
for item in countedSet {
let item = item as! String
let count = countedSet.count(for: item)
let value = NSNumber(integerLiteral: count)
colorCounter.setValue(value, forKey: item)
}
//Sort keys from highest occurence to lowest.
let orderedKeys = colorCounter.keysSortedByValue(comparator: {
(obj1, obj2) in
let x = obj1 as! NSNumber
let y = obj2 as! NSNumber
return x.compare(y)
})
//Check if the color is similar to another one already included.
var ranges = Array<String>()
for key in orderedKeys as! [String] {
let rgb = key.components(separatedBy: ",")
let r = NSString(string: rgb[0]).integerValue
let g = NSString(string: rgb[1]).integerValue
let b = NSString(string: rgb[2]).integerValue
var exclude = false
for rangedkey in ranges {
let rangedRGB = rangedkey.components(separatedBy: ",")
let ranged_r = NSString(string: rangedRGB[0]).integerValue
let ranged_g = NSString(string: rangedRGB[1]).integerValue
let ranged_b = NSString(string: rangedRGB[2]).integerValue
if r >= ranged_r - range && r <= ranged_r + range {
if g >= ranged_g - range && g <= ranged_g + range {
if b >= ranged_b - range && b <= ranged_b + range {
exclude = true
}
}
}
}
if exclude == false {
ranges.append(key)
}
}
//Create the colors and fill them.
var mainColors = Array<UIColor>()
for key in ranges {
let rgb = key.components(separatedBy: ",")
let r = NSString(string: rgb[0]).floatValue
let g = NSString(string: rgb[1]).floatValue
let b = NSString(string: rgb[2]).floatValue
let finalColor = UIColor(red: CGFloat((r / 255)), green: CGFloat((g / 255)), blue: CGFloat((b / 255)), alpha: CGFloat(1.0))
mainColors.append(finalColor)
}
return mainColors
}
最佳答案
这个很棒的开源类似乎运行良好:https://github.com/jathu/UIImageColors
将下面的此类导入到您的项目中。
//
// UIImageColors.swift
// https://github.com/jathu/UIImageColors
//
// Created by Jathu Satkunarajah (@jathu) on 2015-06-11 - Toronto
//
import UIKit
public struct UIImageColors {
public var background: UIColor!
public var primary: UIColor!
public var secondary: UIColor!
public var detail: UIColor!
public init(background: UIColor, primary: UIColor, secondary: UIColor, detail: UIColor) {
self.background = background
self.primary = primary
self.secondary = secondary
self.detail = detail
}
}
public enum UIImageColorsQuality: CGFloat {
case lowest = 50 // 50px
case low = 100 // 100px
case high = 250 // 250px
case highest = 0 // No scale
}
fileprivate struct UIImageColorsCounter {
let color: Double
let count: Int
init(color: Double, count: Int) {
self.color = color
self.count = count
}
}
/*
Extension on double that replicates UIColor methods. We DO NOT want these
exposed outside of the library because they don't make sense outside of the
context of UIImageColors.
*/
fileprivate extension Double {
private var r: Double {
return fmod(floor(self/1000000),1000000)
}
private var g: Double {
return fmod(floor(self/1000),1000)
}
private var b: Double {
return fmod(self,1000)
}
fileprivate var isDarkColor: Bool {
return (r*0.2126) + (g*0.7152) + (b*0.0722) < 127.5
}
fileprivate var isBlackOrWhite: Bool {
return (r > 232 && g > 232 && b > 232) || (r < 23 && g < 23 && b < 23)
}
fileprivate func isDistinct(_ other: Double) -> Bool {
let _r = self.r
let _g = self.g
let _b = self.b
let o_r = other.r
let o_g = other.g
let o_b = other.b
return (fabs(_r-o_r) > 63.75 || fabs(_g-o_g) > 63.75 || fabs(_b-o_b) > 63.75)
&& !(fabs(_r-_g) < 7.65 && fabs(_r-_b) < 7.65 && fabs(o_r-o_g) < 7.65 && fabs(o_r-o_b) < 7.65)
}
fileprivate func with(minSaturation: Double) -> Double {
// Ref: https://en.wikipedia.org/wiki/HSL_and_HSV
// Convert RGB to HSV
let _r = r/255
let _g = g/255
let _b = b/255
var H, S, V: Double
let M = fmax(_r,fmax(_g, _b))
var C = M-fmin(_r,fmin(_g, _b))
V = M
S = V == 0 ? 0:C/V
if minSaturation <= S {
return self
}
if C == 0 {
H = 0
} else if _r == M {
H = fmod((_g-_b)/C, 6)
} else if _g == M {
H = 2+((_b-_r)/C)
} else {
H = 4+((_r-_g)/C)
}
if H < 0 {
H += 6
}
// Back to RGB
C = V*minSaturation
let X = C*(1-fabs(fmod(H,2)-1))
var R, G, B: Double
switch H {
case 0...1:
R = C
G = X
B = 0
case 1...2:
R = X
G = C
B = 0
case 2...3:
R = 0
G = C
B = X
case 3...4:
R = 0
G = X
B = C
case 4...5:
R = X
G = 0
B = C
case 5..<6:
R = C
G = 0
B = X
default:
R = 0
G = 0
B = 0
}
let m = V-C
return (floor((R + m)*255)*1000000)+(floor((G + m)*255)*1000)+floor((B + m)*255)
}
fileprivate func isContrasting(_ color: Double) -> Bool {
let bgLum = (0.2126*r)+(0.7152*g)+(0.0722*b)+12.75
let fgLum = (0.2126*color.r)+(0.7152*color.g)+(0.0722*color.b)+12.75
if bgLum > fgLum {
return 1.6 < bgLum/fgLum
} else {
return 1.6 < fgLum/bgLum
}
}
fileprivate var uicolor: UIColor {
return UIColor(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: 1)
}
fileprivate var pretty: String {
return "\(Int(self.r)), \(Int(self.g)), \(Int(self.b))"
}
}
extension UIImage {
private func resizeForUIImageColors(newSize: CGSize) -> UIImage {
UIGraphicsBeginImageContextWithOptions(newSize, false, 0)
defer {
UIGraphicsEndImageContext()
}
self.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
guard let result = UIGraphicsGetImageFromCurrentImageContext() else {
fatalError("UIImageColors.resizeForUIImageColors failed: UIGraphicsGetImageFromCurrentImageContext returned nil.")
}
return result
}
public func getColors(quality: UIImageColorsQuality = .high, _ completion: @escaping (UIImageColors) -> Void) {
DispatchQueue.global().async {
let result = self.getColors(quality: quality)
DispatchQueue.main.async {
completion(result)
}
}
}
public func getColors(quality: UIImageColorsQuality = .high) -> UIImageColors {
var scaleDownSize: CGSize = self.size
if quality != .highest {
if self.size.width < self.size.height {
let ratio = self.size.height/self.size.width
scaleDownSize = CGSize(width: quality.rawValue/ratio, height: quality.rawValue)
} else {
let ratio = self.size.width/self.size.height
scaleDownSize = CGSize(width: quality.rawValue, height: quality.rawValue/ratio)
}
}
let cgImage = self.resizeForUIImageColors(newSize: scaleDownSize).cgImage!
let width: Int = cgImage.width
let height: Int = cgImage.height
let threshold = Int(CGFloat(height)*0.01)
var proposed: [Double] = [-1,-1,-1,-1]
guard let data = CFDataGetBytePtr(cgImage.dataProvider!.data) else {
fatalError("UIImageColors.getColors failed: could not get cgImage data.")
}
let imageColors = NSCountedSet(capacity: width*height)
for x in 0..<width {
for y in 0..<height {
let pixel: Int = ((width * y) + x) * 4
if 127 <= data[pixel+3] {
imageColors.add((Double(data[pixel+2])*1000000)+(Double(data[pixel+1])*1000)+(Double(data[pixel])))
}
}
}
let sortedColorComparator: Comparator = { (main, other) -> ComparisonResult in
let m = main as! UIImageColorsCounter, o = other as! UIImageColorsCounter
if m.count < o.count {
return .orderedDescending
} else if m.count == o.count {
return .orderedSame
} else {
return .orderedAscending
}
}
var enumerator = imageColors.objectEnumerator()
var sortedColors = NSMutableArray(capacity: imageColors.count)
while let K = enumerator.nextObject() as? Double {
let C = imageColors.count(for: K)
if threshold < C {
sortedColors.add(UIImageColorsCounter(color: K, count: C))
}
}
sortedColors.sort(comparator: sortedColorComparator)
var proposedEdgeColor: UIImageColorsCounter
if 0 < sortedColors.count {
proposedEdgeColor = sortedColors.object(at: 0) as! UIImageColorsCounter
} else {
proposedEdgeColor = UIImageColorsCounter(color: 0, count: 1)
}
if proposedEdgeColor.color.isBlackOrWhite && 0 < sortedColors.count {
for i in 1..<sortedColors.count {
let nextProposedEdgeColor = sortedColors.object(at: i) as! UIImageColorsCounter
if Double(nextProposedEdgeColor.count)/Double(proposedEdgeColor.count) > 0.3 {
if !nextProposedEdgeColor.color.isBlackOrWhite {
proposedEdgeColor = nextProposedEdgeColor
break
}
} else {
break
}
}
}
proposed[0] = proposedEdgeColor.color
enumerator = imageColors.objectEnumerator()
sortedColors.removeAllObjects()
sortedColors = NSMutableArray(capacity: imageColors.count)
let findDarkTextColor = !proposed[0].isDarkColor
while var K = enumerator.nextObject() as? Double {
K = K.with(minSaturation: 0.15)
if K.isDarkColor == findDarkTextColor {
let C = imageColors.count(for: K)
sortedColors.add(UIImageColorsCounter(color: K, count: C))
}
}
sortedColors.sort(comparator: sortedColorComparator)
for color in sortedColors {
let color = (color as! UIImageColorsCounter).color
if proposed[1] == -1 {
if color.isContrasting(proposed[0]) {
proposed[1] = color
}
} else if proposed[2] == -1 {
if !color.isContrasting(proposed[0]) || !proposed[1].isDistinct(color) {
continue
}
proposed[2] = color
} else if proposed[3] == -1 {
if !color.isContrasting(proposed[0]) || !proposed[2].isDistinct(color) || !proposed[1].isDistinct(color) {
continue
}
proposed[3] = color
break
}
}
let isDarkBackground = proposed[0].isDarkColor
for i in 1...3 {
if proposed[i] == -1 {
proposed[i] = isDarkBackground ? 255255255:0
}
}
return UIImageColors(
background: proposed[0].uicolor,
primary: proposed[1].uicolor,
secondary: proposed[2].uicolor,
detail: proposed[3].uicolor
)
}
}
关于ios - 在 Swift 中获取 UIImage 的主要颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41552544/
IO 设备如何知道属于它的内存中的值在memory mapped IO 中发生了变化? ? 例如,假设内存地址 0 专用于保存 VGA 设备的背景颜色。当我们更改 memory[0] 中的值时,VGA
我目前正在开发一个使用Facebook sdk登录(通过FBLoginView)的iOS应用。 一切正常,除了那些拥有较旧版本的facebook的人。 当他们按下“使用Facebook登录”按钮时,他
假设我有: this - is an - example - with some - dashesNSRange将使用`rangeOfString:@“-”拾取“-”的第一个实例,但是如果我只想要最后
Card.io SDK提供以下详细信息: 卡号,有效期,月份,年份,CVV和邮政编码。 如何从此SDK获取国家名称。 - (void)userDidProvideCreditCardInfo:(Car
iOS 应用程序如何从网络服务下载图片并在安装过程中将它们安装到用户的 iOS 设备上?可能吗? 最佳答案 您无法控制应用在用户设备上的安装,因此无法在安装过程中下载其他数据。 只需在安装后首次启动应
我曾经开发过一款企业版 iOS 产品,我们公司曾将其出售给大型企业,供他们的员工使用。 该应用程序通过 AppStore 提供,企业用户获得了公司特定的配置文件(包含应用程序配置文件)以启用他们有权使
我正在尝试将 Card.io SDK 集成到我的 iOS 应用程序中。我想为 CardIO ui 做一个简单的本地化,如更改取消按钮标题或“在此保留信用卡”提示文本。 我在 github 上找到了这个
我正在使用 CardIOView 和 CardIOViewDelegate 类,没有可以设置为 YES 的 BOOL 来扫描 collectCardholderName。我可以看到它在 CardIOP
我有一个集成了通话工具包的 voip 应用程序。每次我从我的 voip 应用程序调用时,都会在 native 电话应用程序中创建一个新的最近通话记录。我在 voip 应用程序中也有自定义联系人(电话应
iOS 应用程序如何知道应用程序打开时屏幕上是否已经有键盘?应用程序运行后,它可以接收键盘显示/隐藏通知。但是,如果应用程序在分屏模式下作为辅助应用程序打开,而主应用程序已经显示键盘,则辅助应用程序不
我在模拟器中收到以下错误: ImageIO: CGImageReadSessionGetCachedImageBlockData *** CGImageReadSessionGetCachedIm
如 Apple 文档所示,可以通过 EAAccessory Framework 与经过认证的配件(由 Apple 认证)进行通信。但是我有点困惑,因为一些帖子告诉我它也可以通过 CoreBluetoo
尽管现在的调试器已经很不错了,但有时找出应用程序中正在发生的事情的最好方法仍然是古老的 NSLog。当您连接到计算机时,这样做很容易; Xcode 会帮助弹出日志查看器面板,然后就可以了。当您不在办公
在我的 iOS 应用程序中,我定义了一些兴趣点。其中一些有一个 Kontakt.io 信标的名称,它绑定(bind)到一个特定的 PoI(我的意思是通常贴在信标标签上的名称)。现在我想在附近发现信标,
我正在为警报提示创建一个 trigger.io 插件。尝试从警报提示返回数据。这是我的代码: // Prompt + (void)show_prompt:(ForgeTask*)task{
您好,我是 Apple iOS 的新手。我阅读并搜索了很多关于推送通知的文章,但我没有发现任何关于 APNS 从 io4 到 ios 6 的新更新的信息。任何人都可以向我提供 APNS 如何在 ios
UITabBar 的高度似乎在 iOS 7 和 8/9/10/11 之间发生了变化。我发布这个问题是为了让其他人轻松找到答案。 那么:在 iPhone 和 iPad 上的 iOS 8/9/10/11
我想我可以针对不同的 iOS 版本使用不同的 Storyboard。 由于 UI 的差异,我将创建下一个 Storyboard: Main_iPhone.storyboard Main_iPad.st
我正在写一些东西,我将使用设备的 iTunes 库中的一部分音轨来覆盖 2 个视频的组合,例如: AVMutableComposition* mixComposition = [[AVMutableC
我创建了一个简单的 iOS 程序,可以顺利编译并在 iPad 模拟器上运行良好。当我告诉 XCode 4 使用我连接的 iPad 设备时,无法编译相同的程序。问题似乎是当我尝试使用附加的 iPad 时
我是一名优秀的程序员,十分优秀!