如何在iOS中的两个UIColors之间获得中间色

时间:2015-11-04 10:24:09

标签: ios objective-c uicolor

如果我给两种颜色

UIColor *color1 = [UIColor blackColor];
UIColor *color2 = [UIColor whiteColor];

我应该得到grayColor,我该如何实现呢?

3 个答案:

答案 0 :(得分:13)

在"之间找到"的简单方法。是平均四个组成部分,如下:

UIColor *color1 = [UIColor blackColor];
UIColor *color2 = [UIColor whiteColor];
CGFloat r1, r2, g1, g2, b1, b2, a1, a2;
[color1 getRed:&r1 green:&g1 blue:&b1 alpha:&a1];
[color2 getRed:&r2 green:&g2 blue:&b2 alpha:&a2];
UIColor *avg = [UIColor colorWithRed:(r1+r2)/2.0f
                              green:(g1+g2)/2.0f
                               blue:(b1+b2)/2.0f
                              alpha:(a1+a2)/2.0f];

请注意,这会产生一个中点RGBA颜色空间,它只是众多可能颜色空间中的一个。在其他颜色空间中平均分量将导致不同的结果。

答案 1 :(得分:3)

回答 Swift 4 +

func blend(colors: [UIColor]) -> UIColor {
    let componentsSum = colors.reduce((red: CGFloat(0), green: CGFloat(0), blue: CGFloat(0))) { (temp, color) in
      guard let components = color.cgColor.components else { return temp }
      return (temp.0 + components[0], temp.1 + components[1], temp.2 + components[2])
    }
    let components = (red: componentsSum.red / CGFloat(colors.count) ,
                      green: componentsSum.green / CGFloat(colors.count),
                      blue: componentsSum.blue / CGFloat(colors.count))
    return UIColor(red: components.red, green: components.green, blue: components.blue, alpha: 1)
  }

它融合了你想要的颜色

答案 2 :(得分:0)

这里的Swift实现可以安全使用。适用于不同颜色空间的颜色,但可以混合在RGBA中:

import scrapy, docx, time
import subprocess as sp

class FanfictionDownloader(scrapy.Spider):
    name = "fanfiction"
    storyNum = 0
    nextPage = False
    urls = []
    docText = ''
    title = ''

    def start_requests(self):
        sp.call('cls', shell=True)
        self.urls = list(str(input("Enter url seperated by a comma and space (, ): ")).split(', '))
        for url in self.urls:
            if self.urls[self.storyNum].startswith('https://www.fanfiction.net/s/'):
                yield scrapy.Request(url=url, callback=self.fanfiction)
            elif self.urls[self.storyNum].startswith('https://www.wattpad.com/'):
                yield scrapy.Request(url=url, callback=self.wattpad)
            else:
                print('Not a valid link, ending downloader.')
                time.sleep(5)
                quit()
                sp.call('cls', shell=True)

    def fanfiction(self, response):
        self.storyNum += 1
        doc = docx.Document()
        chapters = ''
        totalChapters = 0
        currentChapter = 1
        i = 0
        for para in response.css('div#storytext > p'):
            text = (para.xpath('text() | */text() | */*/text()').getall())
            self.title = (response.xpath('//*[@id="profile_top"]/b/text()').get())
            storyId = ((response.xpath('//*[@id="profile_top"]/span[4]/text()[5]').get()).replace(' - id: ', ''))
            chapters = (response.xpath('//*[@id="chap_select"]/option/text()').getall())
            totalChapters = len(chapters[0:int(len(chapters) / 2)])
            finalText = [
                [x.replace('\u00ef', 'ï').replace('\u2013', '–').replace('\u2026', '...') for x in text],
                ['Story %s: %s' % (self.storyNum,  self.urls[self.storyNum - 1])],
                ['Title: %s' % (self.title)],
                ['Story ID: %s' % (storyId)],
                ['Total Chapters: %s' % (totalChapters)],
                ['Chapter Names: %s' % [chapters[0:int(len(chapters) / 2)]]],
            ]
            if len(finalText[0][0]) > 1:
                self.docText = (''.join(finalText[0][0:]))
            else:
                self.docText = finalText[0][0]
            if self.nextPage == False:
                doc.add_paragraph(self.docText)
            else:
                doc.add_page_break(self.docText)
                self.nextPage = False
                doc.add_paragraph()
            sp.call('cls', shell=True)
            doc.save('./../%s.docx' % (self.title))
            i += 1
            yield {'line ' + str(i): finalText}
            sp.call('cls', shell=True)

    def wattpad(self, response):
        pass

使用:

func + (left: UIColor, right: UIColor) -> UIColor {
    var (r1, g1, b1, a1) = (CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0))
    var (r2, g2, b2, a2) = (CGFloat(0), CGFloat(0), CGFloat(0), CGFloat(0))
    left.getRed(&r1, green: &g1, blue: &b1, alpha: &a1)
    right.getRed(&r2, green: &g2, blue: &b2, alpha: &a2)
    return UIColor(red: (r1 + r2)/2, green: (g1 + g2)/2, blue: (b1 + b2)/2, alpha: (a1 + a2)/2)
}

旧答案:

    view.backgroundColor = .red + .white

但是它仅适用于一种颜色空间的颜色,否则它将返回nil。 这里是使用示例:

extension UIColor {

    func blended(with color: UIColor) -> UIColor? {
        guard cgColor.colorSpace == color.cgColor.colorSpace else { return nil }
        return UIColor(cgColor: CGColor(colorSpace: cgColor.colorSpace!, components:
            zip(cgColor.components!, color.cgColor.components!).map { ($0 + $1) / 2 }
        )!)
    }
}