# 4 使用圖片,文字,emoji,邊框 & 圓角製作漂亮卡片
Published in
6 min readDec 8, 2022
目的:練習用程式做出含圖片、文字、邊框的卡片,這次也使用到mask遮罩的部分,還有CGAffineTransform的旋轉功能
這次主題是peter來要求的XD,想讓我這個直男用程式做出浪漫卡片
以下是這次code(裡面大部分都有註記)
import UIKit
import Foundation
//設定image
let coupleImage = UIImage(named: "couple.jpg")
//轉成imageView
let coupleImageView = UIImageView(image: coupleImage)
//設定圖片的寬高
coupleImageView.frame = CGRect(x: 0, y: 0, width: 450, height: 600)
//維持比例但上下或左右留白.scaleAspectFit
coupleImageView.contentMode = .scaleAspectFit
//維持比例並填滿frame的框框,超出的部分被切掉
coupleImageView.contentMode = .scaleAspectFill
//加入mask要用的圖片
let heartImage = UIImage(named: "heart.png")
let heartImageView = UIImageView(image: heartImage)
//將圖幅全部修改至統一大小
coupleImageView.frame=CGRect(x: 0, y: 0, width: 500, height: 500)
heartImageView.frame=coupleImageView.frame
//調整內容顯示
coupleImageView.contentMode = .scaleAspectFill
//設定以愛心圖形為主的遮罩,並將遮罩層貼至底圖上
coupleImageView.mask = heartImageView
//透明度 : alpha(0~1)
coupleImageView.alpha = 0.5
//顯示文字text
let messageLabel = UILabel(frame: CGRect(x: 190, y: 350, width: 150, height: 30))
messageLabel.text = "兩週年快樂"
//文字顏色textColor
messageLabel.textColor = UIColor(red: 1, green: 120/255, blue: 1, alpha: 1)
//文字大小font
messageLabel.font = UIFont.systemFont(ofSize: 28)
//把文字顯現
coupleImageView.addSubview(messageLabel)
//邊框寬度borderWidth
coupleImageView.layer.borderWidth = 10
//邊框顏色borderColor
coupleImageView.layer.borderColor = CGColor(red: 1, green: 0, blue: 0, alpha: 1)
//圓角cornerRadius
coupleImageView.layer.cornerRadius = 50
coupleImageView.clipsToBounds = true
//加入 emoji
let heartLabel = UILabel(frame: CGRect(x: 215, y: 100, width: 50, height: 40))
heartLabel.text = " 💜 "
heartLabel.font = UIFont.systemFont(ofSize: 35 )
coupleImageView.addSubview(heartLabel)
//旋轉
heartLabel.transform = CGAffineTransform(rotationAngle: .pi / 180 * 45)
//在四角各加入圖案
var loveLabel = UILabel(frame: CGRect(x: 30, y: 30, width: 30, height: 30))
loveLabel.text = "👩❤️👨"
loveLabel.font = UIFont.systemFont(ofSize: 25)
coupleImageView.addSubview(loveLabel)
loveLabel.transform = CGAffineTransform(rotationAngle: .pi / 180 * 10)
loveLabel = UILabel(frame: CGRect(x: 450, y: 30, width: 30, height: 30))
loveLabel.text = "👩❤️👩"
loveLabel.font = UIFont.systemFont(ofSize: 25)
coupleImageView.addSubview(loveLabel)
loveLabel.transform = CGAffineTransform(rotationAngle: .pi / 180 * 45)
loveLabel = UILabel(frame: CGRect(x: 30, y: 320, width: 30, height: 30))
loveLabel.text = "👨❤️👨"
loveLabel.font = UIFont.systemFont(ofSize: 25)
coupleImageView.addSubview(loveLabel)
loveLabel.transform = CGAffineTransform(rotationAngle: .pi / 180 * 90)
loveLabel = UILabel(frame: CGRect(x: 450, y: 320, width: 30, height: 30))
loveLabel.text = "👩❤️💋👨"
loveLabel.font = UIFont.systemFont(ofSize: 25)
coupleImageView.addSubview(loveLabel)
loveLabel.transform = CGAffineTransform(rotationAngle: .pi / 180 * 150)
coupleImageView
結果呈現