GVKun编程网logo

如何在Swift中使用UIColorFromRGB?(swiftui form)

12

在本文中,您将会了解到关于如何在Swift中使用UIColorFromRGB?的新资讯,同时我们还将为您解释swiftuiform的相关在本文中,我们将带你探索如何在Swift中使用UIColorFr

在本文中,您将会了解到关于如何在Swift中使用UIColorFromRGB?的新资讯,同时我们还将为您解释swiftui form的相关在本文中,我们将带你探索如何在Swift中使用UIColorFromRGB?的奥秘,分析swiftui form的特点,并给出一些关于ios – 在Swift中使用CIColorCube过滤器、ios – 在Swift中使用CIColorMatrix过滤器、ios – 在Swift中使用UI_USER_INTERFACE_IDIOM()检测当前设备、ios – 在Swift中使用URLComponents编码”的实用技巧。

本文目录一览:

如何在Swift中使用UIColorFromRGB?(swiftui form)

如何在Swift中使用UIColorFromRGB?(swiftui form)

在Objective-C中,我们使用以下代码为视图设置RGB颜色代码:

#define UIColorFromRGB(rgbValue)        [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]view.backgroundColor=UIColorFromRGB(0x209624);

如何在Swift中使用它?

答案1

小编典典

这是该函数的Swift版本(用于获取UInt值的UIColor表示形式):

func UIColorFromRGB(rgbValue: UInt) -> UIColor {    return UIColor(        red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,        green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,        blue: CGFloat(rgbValue & 0x0000FF) / 255.0,        alpha: CGFloat(1.0)    )}view.backgroundColor = UIColorFromRGB(0x209624)

ios – 在Swift中使用CIColorCube过滤器

ios – 在Swift中使用CIColorCube过滤器

我想让CIColorCube过滤器工作.但是,Apple文档仅提供了一个解释不佳的参考示例:

// Allocate memory
const unsigned int size = 64;
float *cubedata = (float *)malloc (size * size * size * sizeof (float) * 4);
float rgb[3],hsv[3],*c = cubedata;

// Populate cube with a simple gradient going from 0 to 1
for (int z = 0; z < size; z++){
    rgb[2] = ((double)z)/(size-1); // Blue value
    for (int y = 0; y < size; y++){
        rgb[1] = ((double)y)/(size-1); // Green value
        for (int x = 0; x < size; x ++){
            rgb[0] = ((double)x)/(size-1); // Red value
            // Convert RGB to HSV
            // You can find publicly available rgbToHSV functions on the Internet
            rgbToHSV(rgb,hsv);
            // Use the hue value to determine which to make transparent
            // The minimum and maximum hue angle depends on
            // the color you want to remove
            float alpha = (hsv[0] > minHueAngle && hsv[0] < maxHueAngle) ? 0.0f: 1.0f;
            // Calculate premultiplied alpha values for the cube
            c[0] = rgb[0] * alpha;
            c[1] = rgb[1] * alpha;
            c[2] = rgb[2] * alpha;
            c[3] = alpha;
            c += 4; // advance our pointer into memory for the next color value
        }
    }
}
// Create memory with the cube data
NSData *data = [NSData dataWithBytesNocopy:cubedata
                       length:cubedataSize
                       freeWhenDone:YES];
CIColorCube *colorCube = [CIFilter filterWithName:@"CIColorCube"];
[colorCube setValue:@(size) forKey:@"inputCubedimension"];
// Set data for cube
[colorCube setValue:data forKey:@"inputCubedata"];

所以我试图用以下内容将其翻译成Swift:

var filter = CIFilter(name: "CIColorCube")
    filter.setValue(ciImage,forKey: kCIInputimageKey)
    filter.setDefaults()

    var size: UInt = 64
    var floatSize = UInt(sizeof(Float))
    var cubedataSize:size_t = size * size * size * floatSize * 4
    var colorCubedata:Array<Float> = [
    0,1,1
    ]

    var cubedata:NSData = NSData(bytesNocopy: colorCubedata,length: cubedataSize)

但是,在尝试创建多维数据集数据时出现错误:

"Extra argument 'bytesNocopy' in call"

基本上我创建的cubedata错了.你能告诉我如何在Swift中正确创建cubedata对象吗?

谢谢!

解决方法

看起来你是在色度键过滤器配方 described here之后.这里有一些有效的代码.你得到一个透明颜色的过滤器,由它的HSV角度描述:

func RGBtoHSV(r : Float,g : Float,b : Float) -> (h : Float,s : Float,v : Float) {
    var h : CGFloat = 0
    var s : CGFloat = 0
    var v : CGFloat = 0
    let col = UIColor(red: CGFloat(r),green: CGFloat(g),blue: CGFloat(b),alpha: 1.0)
    col.getHue(&h,saturation: &s,brightness: &v,alpha: nil)
    return (Float(h),Float(s),Float(v))
}

func colorCubeFilterForChromakey(hueAngle: Float) -> CIFilter {

    let hueRange: Float = 60 // degrees size pie shape that we want to replace
    let minHueAngle: Float = (hueAngle - hueRange/2.0) / 360
    let maxHueAngle: Float = (hueAngle + hueRange/2.0) / 360

    let size = 64
    var cubedata = [Float](repeating: 0,count: size * size * size * 4)
    var rgb: [Float] = [0,0]
    var hsv: (h : Float,v : Float)
    var offset = 0

    for z in 0 ..< size {
        rgb[2] = Float(z) / Float(size) // blue value
        for y in 0 ..< size {
            rgb[1] = Float(y) / Float(size) // green value
            for x in 0 ..< size {

                rgb[0] = Float(x) / Float(size) // red value
                hsv = RGBtoHSV(r: rgb[0],g: rgb[1],b: rgb[2])
                // the condition checking hsv.s may need to be removed for your use-case
                let alpha: Float = (hsv.h > minHueAngle && hsv.h < maxHueAngle && hsv.s > 0.5) ? 0 : 1.0 

                cubedata[offset] = rgb[0] * alpha
                cubedata[offset + 1] = rgb[1] * alpha
                cubedata[offset + 2] = rgb[2] * alpha
                cubedata[offset + 3] = alpha
                offset += 4
            }
        }
    }
    let b = cubedata.withUnsafeBufferPointer { Data(buffer: $0) }
    let data = b as NSData

    let colorCube = CIFilter(name: "CIColorCube",withInputParameters: [
        "inputCubedimension": size,"inputCubedata": data
    ])
    return colorCube!
}

然后进行过滤器调用

让chromakeyFilter = colorCubeFilterForChromakey(hueAngle:120)

我使用120作为标准绿屏.

ios – 在Swift中使用CIColorMatrix过滤器

ios – 在Swift中使用CIColorMatrix过滤器

以下 Swift函数应该使用指定的’tintColor’为灰度图像’greyImage’着色:

import UIKit

func colorizeImage(greyImage : UIImage,tintColor : UIColor) -> UIImage? {

    let colorMatrixFilter = CIFilter(name: "CIColorMatrix")

    var r:CGFloat = 0
    var g:CGFloat = 0
    var b:CGFloat = 0
    var a:CGFloat = 0
    tintColor.getRed(&r,green:&g,blue:&b,alpha:&a)

    colorMatrixFilter.setDefaults()
    colorMatrixFilter.setValue(greyImage,forKey:"inputimage") //kCIInputimageKey)
    colorMatrixFilter.setValue(CIVector(x:r,y:0,z:0,w:0),forKey:"inputRVector")
    colorMatrixFilter.setValue(CIVector(x:0,y:g,forKey:"inputGVector")
    colorMatrixFilter.setValue(CIVector(x:0,z:b,forKey:"inputBVector")
    colorMatrixFilter.setValue(CIVector(x:0,w:a),forKey:"inputAVector")

    if let ciImage =  colorMatrixFilter.outputimage {
        return UIImage(CIImage: ciImage);
    }

    return nil;
}

颜色为UIColor.orangeColor()(r = 1,g = 0.5,b = 0,a = 1),灰度图像正常,因为它在送到ImageView时可以正确显示.

看起来提供了所有必需的密钥并且密钥分配顺利进行(BTW过滤器检查密钥的有效性,还是采取一切措施?),但是读取’outputimage’属性会产生SIGABRT和以下控制台消息:

2015-05-02 13:04:07.319 MyApp[436:8241] -[UIImage _internalRepresentation]: unrecognized selector sent to instance 0x7fd5b3ca82b0
2015-05-02 13:04:07.629 MyApp[436:8241] *** Terminating app due to uncaught exception 'NSinvalidargumentexception',reason: '-[UIImage _internalRepresentation]: unrecognized selector sent to instance 0x7fd5b3ca82b0'
*** First throw call stack:
(
    0   CoreFoundation                      0x00000001087abf35 __exceptionPreprocess + 165
    1   libobjc.A.dylib                     0x000000010a56cbb7 objc_exception_throw + 45
    2   CoreFoundation                      0x00000001087b304d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205
    3   CoreFoundation                      0x000000010870b27c ___forwarding___ + 988
    4   CoreFoundation                      0x000000010870ae18 _CF_forwarding_prep_0 + 120
    5   CoreImage                           0x0000000108bd30fe -[CIColorMatrix outputimage] + 885
    6   MyApp                            0x00000001085c182d _TF8MyApp13colorizeImageFTCSo7UIImageCSo7UIColor_GSqS0__ + 4733
    7   MyApp                            0x00000001085c2b59

解决方法

问题是 CIColorMatrix期望参数inputimage应该是CIImage对象而不是UIImage(greyImage).

更新:Swift 3或更高版本

extension UIImage {
    func colorized(with color: UIColor) -> UIImage? {
        guard
            let ciimage = CIImage(image: self),let colorMatrix = CIFilter(name: "CIColorMatrix")
        else { return nil }
        var r: CGFloat = 0,g: CGFloat = 0,b: CGFloat = 0,a: CGFloat = 0
        color.getRed(&r,green: &g,blue: &b,alpha: &a)
        colorMatrix.setDefaults()
        colorMatrix.setValue(ciimage,forKey: "inputimage")
        colorMatrix.setValue(CIVector(x: r,y: 0,z: 0,w: 0),forKey: "inputRVector")
        colorMatrix.setValue(CIVector(x: 0,y: g,forKey: "inputGVector")
        colorMatrix.setValue(CIVector(x: 0,z: b,forKey: "inputBVector")
        colorMatrix.setValue(CIVector(x: 0,w: a),forKey: "inputAVector")
        if let ciimage = colorMatrix.outputimage {
            return UIImage(ciImage: ciimage)
        }
        return nil
    }
}
let profilePicture = UIImage(data: try!  Data(contentsOf: URL(string: "http://i.stack.imgur.com/Xs4RX.jpg")!))!
profilePicture.colorized(with: .orange)

enter image description here

ios – 在Swift中使用UI_USER_INTERFACE_IDIOM()检测当前设备

ios – 在Swift中使用UI_USER_INTERFACE_IDIOM()检测当前设备

什么是相当于UI_USER_INTERFACE_IdioM()在Swift中检测iPhone和iPad之间?

我得到一个使用未解决的标识符错误时编译在Swift。

解决方法

当使用Swift时,可以使用枚举UIUserInterfaceIdiom,定义如下:

enum UIUserInterfaceIdiom : Int {
    case Unspecified

    case Phone // iPhone and iPod touch style UI
    case Pad // iPad style UI
}

所以你可以使用它:

UIDevice.currentDevice().userInterfaceIdiom == .Pad
UIDevice.currentDevice().userInterfaceIdiom == .Phone
UIDevice.currentDevice().userInterfaceIdiom == .Unspecified

或者用一个Switch语句:

switch UIDevice.currentDevice().userInterfaceIdiom {
    case .Phone:
        // It's an iPhone
    case .Pad:
        // It's an iPad
    case .Unspecified:
        // Uh,oh! What Could it be?
    }

UI_USER_INTERFACE_IdioM()是一个Objective-C宏,定义为:

#define UI_USER_INTERFACE_IdioM() \ ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? \ [[UIDevice currentDevice] userInterfaceIdiom] : \ UIUserInterfaceIdiomPhone)

此外,请注意,即使使用Objective-C,UI_USER_INTERFACE_IdioM()宏仅在定位iOS 3.2及更低版本时才需要。部署到iOS 3.2及更高版本时,可以直接使用[UIDevice userInterfaceIdiom]。

ios – 在Swift中使用URLComponents编码”

ios – 在Swift中使用URLComponents编码”

这是我如何将查询参数添加到基本URL:
let baseURL: URL = ...
let queryParams: [AnyHashable: Any] = ...
var components = URLComponents(url: baseURL,resolvingAgainstBaseURL: false)
components?.queryItems = queryParams.map { URLQueryItem(name: $0,value: "\($1)") }
let finalURL = components?.url

当其中一个值包含符号时​​,就会出现问题.由于某种原因,它在最终的URL中没有编码为+,而是保留.如果我自己编码并传递+,则NSURL编码%,’plus’变为%2B.

问题是我如何在NSURL的实例中拥有+?

附:我知道,如果我自己构造一个查询字符串,然后简单地将结果传递给NSURL的构造函数init?(字符串:),我甚至不会遇到这个问题.

解决方法

正如在其他答案中指出的那样,“”字符在
一个查询字符串,这也在
query​Items文档.

另一方面,
W3C recommendations for URI addressing
说明

Within the query string,the plus sign is reserved as shorthand notation for a space. Therefore,real plus signs must be encoded. This method was used to make query URIs easier to pass in systems which did not allow spaces.

这可以通过“手动”构建来实现
百分比编码的查询字符串,使用自定义字符集:

let queryParams = ["foo":"a+b","bar": "a-b","baz": "a b"]
var components = URLComponents()

var cs = CharacterSet.urlQueryAllowed
cs.remove("+")

components.scheme = "http"
components.host = "www.example.com"
components.path = "/somepath"
components.percentEncodedQuery = queryParams.map {
    $0.addingPercentEncoding(withAllowedCharacters: cs)!
    + "=" + $1.addingPercentEncoding(withAllowedCharacters: cs)!
}.joined(separator: "&")

let finalURL = components.url
// http://www.example.com/somepath?bar=a-b&baz=a%20b&foo=a%2Bb

另一种选择是对生成的加号进行“后编码”
百分比编码的查询字符串:

let queryParams = ["foo":"a+b","baz": "a b"]
var components = URLComponents()
components.scheme = "http"
components.host = "www.example.com"
components.path = "/somepath"
components.queryItems = queryParams.map { URLQueryItem(name: $0,value: $1) }
components.percentEncodedQuery = components.percentEncodedQuery?
    .replacingOccurrences(of: "+",with: "%2B")

let finalURL = components.url
print(finalURL!)
// http://www.example.com/somepath?bar=a-b&baz=a%20b&foo=a%2Bb

关于如何在Swift中使用UIColorFromRGB?swiftui form的问题就给大家分享到这里,感谢你花时间阅读本站内容,更多关于ios – 在Swift中使用CIColorCube过滤器、ios – 在Swift中使用CIColorMatrix过滤器、ios – 在Swift中使用UI_USER_INTERFACE_IDIOM()检测当前设备、ios – 在Swift中使用URLComponents编码”等相关知识的信息别忘了在本站进行查找喔。

本文标签: