LoginSignup
28
10

More than 1 year has passed since last update.

SwiftUI 金銀銅 をコードで表現する

Last updated at Posted at 2021-05-15

はじめに

日本中が東京オリンピック応援ムードで大盛り上がり。
街行く人達の話題も五輪のテーマで持ちきりです。
どの選手がメダルを取るのか、今から超楽しみで夜も眠れません😂
さて, そんな景気の良い日本を後押しすべく iOSアプリ でも 金色, 銀色, 銅色 を使いたい、 だからこそ SwiftUI で Gold, Silver, Bronze を使っていきたいんです。

GSVImage.png

使い方

色を塗りたい View に対して .shine(ShineColor) を付加します。

  • 金色: .shine(.gold)
  • 銀色: .shine(.silver)
  • 銅色: .shine(.bronze)
Sample.swift
// 例: 金色のテキスト "GOLD"
Text("GOLD")
    .shine(.gold)

// 例: 銀色の四角形 ■
Rectangle()
    .shine(.silver)

コピペ用コード

丸々コピペして、プロジェクト内のどこかにおいて下さい。

ShineColor.Swift
import SwiftUI
enum ShineColor {
    case gold
    case silver
    case bronze
    var colors: [Color] {
        switch self {
        case .gold: return [ Color(hex: 0xDBB400),
                             Color(hex: 0xEFAF00),
                             Color(hex: 0xF5D100),
                             Color(hex: 0xE0CA82),
                             Color(hex: 0xD1AE15),
                             Color(hex: 0xDBB400),
        ]
        case .silver: return [ Color(hex: 0x70706F),
                               Color(hex: 0x7D7D7A),
                               Color(hex: 0xB3B6B5),
                               Color(hex: 0x8E8D8D),
                               Color(hex: 0xB3B6B5),
                               Color(hex: 0xA1A2A3),
        ]
        case .bronze: return [ Color(hex: 0x804A00),
                               Color(hex: 0x9C7A3C),
                               Color(hex: 0xB08D57),
                               Color(hex: 0x895E1A),
                               Color(hex: 0x804A00),
                               Color(hex: 0xB08D57),
        ]}
    }
    var linearGradient: LinearGradient
    {
        return LinearGradient(
            gradient: Gradient(colors: self.colors),
            startPoint: .topLeading,
            endPoint: .bottomTrailing
        )
    }
}
extension View {
    func shine(_ color: ShineColor) -> some View {
        ZStack {
            self.opacity(0)
            color.linearGradient.mask(self)
        }.fixedSize()
    }
}
fileprivate extension Color {
    init(hex: UInt, alpha: Double = 1) {
        self.init( .sRGB,
                   red: Double((hex >> 16) & 0xff) / 255,
                   green: Double((hex >> 08) & 0xff) / 255,
                   blue: Double((hex >> 00) & 0xff) / 255,
                   opacity: alpha )
    }
}

さいごに

不要不急の外出は控えましょう。

28
10
4

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
28
10