LoginSignup
0
1

More than 1 year has passed since last update.

RGBを用いて色を決める(UIColor)

Posted at

今回の内容

  • アプリを作ってる時に、どうすればカスタムされた色をコードで使えるのか気になったので調べてみました。

  • UIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)を用いて色を変えてみます。

RGBとは

  • なんとなく分かりそうですが、RはRed、GはGreen、BはBlueです。

  • この3色の組み合わせを用いて、さまざまな色を表示することが出来ます。

コードと簡単解説

  • 今回は、コードで作成したUISegmentedControlのselectedSegmentTintColorでカスタムした色を使いたいので、UIColor(red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)を使用します。

  • 今回は、この画像の赤い色を表示します
    228E7FD3-554A-4C93-BBCE-ADA4C04B2736_4_5005_c.jpeg

   uiSegmentControl.selectedSegmentTintColor = UIColor(red: 1.0, green: 0.40, blue: 0.51, alpha: 1.0)
  • ここで、red: 1.0, green: 0.40, blue: 0.51, alpha: 1.0の値を簡単に調べる方法を書きます

    • Main.storyboardにViewなどの色を設定できるものを作成します。
    • 色をcustomで選択します。(今回はViewのbackgroundColorに色を設定したと仮定)
    • viewDidLoadなどでprint(self.view.backgroundColor as Any)を使用するとデバッグエリアに下記のように表示されます。
    • 左からRGBと一番右はalphaです。
    • 表示された数字の部分を四捨五入して使います。(例:0.405169を0.40にして使います) 
   (UIExtendedSRGBColorSpace 1 0.405169 0.512318 1)

実際のコード

class SegmentedControl{

    var uiSegmentControl = UISegmentedControl()

    let realmCRUDModel = RealmCRUDModel()

}

extension SegmentedControl{

    func createSegment(targetView:UIView){

        realmCRUDModel.readRealmTag()

        uiSegmentControl.removeAllSegments()

        for segmentCount in 0...realmCRUDModel.realmTagArray.count - 1{

            uiSegmentControl.insertSegment(withTitle: realmCRUDModel.realmTagArray[segmentCount], at: segmentCount, animated: true)

        }

        uiSegmentControl.frame = CGRect(x: targetView.bounds.minX + 5, y: targetView.bounds.minY + 97, width: targetView.frame.size.width - 10, height: 32)

        uiSegmentControl.selectedSegmentTintColor = UIColor(red: 1.0, green: 0.40, blue: 0.51, alpha: 1.0) 

        targetView.addSubview(uiSegmentControl)
    }

}

終わり

Qiitaを書いてると無意識に書く内容を何回も呟いたり、考えたりするので
いつの間にか覚えてることが最近よくある
ご指摘、ご質問などありましたら、コメントまでお願い致します。

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1