728x90
๋ฐ˜์‘ํ˜•

๊ฐœ๋ฐœ์„ ์ง„ํ–‰ํ•˜๋˜ ์ค‘, ๋ฒ„ํŠผ ์•ˆ์— ์ด๋ฏธ์ง€๋ฅผ ๋„ฃ๊ณ  ์‹ถ์€๋ฐ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๋ฌธ์ œ๊ฐ€ ๋ฐœ์ƒํ–ˆ๋‹ค.

์ด ๋ฌธ์ œ๋Š” ์ด์ „์— ํ•ด๊ฒฐํ•œ ์ ์ด ์žˆ์—ˆ๋Š”๋ฐ ์–ด๋–ป๊ฒŒ ํ–ˆ๋Š”์ง€ ๊ธฐ์–ต์ด ๋‚˜์งˆ ์•Š์•˜๋‹ค.

 

์•ž์œผ๋กœ ๋น„์Šทํ•œ ์ƒํ™ฉ์„ ๋งˆ์ฃผํ–ˆ์„ ๋•Œ ์ฐพ์•„๋ณด๊ธฐ ์œ„ํ•ด ์ •๋ฆฌํ•œ๋‹ค!!

 

์ด๋ฏธ์ง€ ํฌ๊ธฐ ์กฐ์ •ํ•˜๊ธฐ

์ด๋ฏธ์ง€ ํฌ๊ธฐ๋ฅผ ์กฐ์ •ํ•˜๋Š” ๋ฐฉ๋ฒ•์€ ๋จผ์ € extension์„ ์ถ”๊ฐ€ํ•ด์ค˜์•ผ ํ•œ๋‹ค.

import UIKit

extension UIImage {
    func resize(targetSize: CGSize) -> UIImage? {
        let rect = CGRect(origin: .zero, size: targetSize)
        UIGraphicsBeginImageContextWithOptions(targetSize, false, 0.0)
        self.draw(in: rect)
        let resizedImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return resizedImage
    }
}

์ด๋ ‡๊ฒŒ UIImage ์ต์Šคํ…์…˜์„ ๋งŒ๋“ค์–ด์ค€๋‹ค.

 

 

 

๊ทธ๋ฆฌ๊ณ , ์›ํ•˜๋Š” ๋ฒ„ํŠผ์„ ์„ธํŒ…ํ•˜๋Š” ๋ถ€๋ถ„์—์„œ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

private let settingButton = UIButton().then {
    let imageSize = CGSize(width: 100, height: 100) // 1
    let resizedImage = UIImage(systemName: "gearshape")?.resize(targetSize: imageSize) // 2
    $0.imageView?.contentMode = .scaleToFill // 3
    $0.setImage(resizedImage, for: .normal) // 4
}

(๋‚˜๋Š” then์„ ์‚ฌ์šฉํ•˜์˜€๋‹ค.)

1. ๋จผ์ €, ์ด๋ฏธ์ง€ ํฌ๊ธฐ๋ฅผ CGSize๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ์„ค์ •ํ•ด์ค€๋‹ค. ์œ„ ์ฝ”๋“œ์—์„œ๋Š” ๋„ˆ๋น„์™€ ๋†’์ด ๋ชจ๋‘ 100์œผ๋กœ ์„ค์ •๋˜์—ˆ๋‹ค.

2. ๊ทธ๋ฆฌ๊ณ , ํฌ๊ธฐ๋ฅผ ์กฐ์ •ํ•˜๊ณ ์ž ํ•˜๋Š” ์ด๋ฏธ์ง€๋ฅผ ๊ฐ€์ ธ์™€ ์•„๊นŒ ๋งŒ๋“ค์–ด๋‘” extension์„ ์‚ฌ์šฉํ•ด์ค€๋‹ค.

3. ์ด์ œ ์ด๋ฏธ์ง€๋ทฐ์˜ contentMode๋ฅผ scaleToFill๋กœ ์„ค์ •ํ•ด ์ด๋ฏธ์ง€๊ฐ€ ๋ทฐ์— ๊ฐ€๋“ ์ฐจ๋„๋ก ํ•œ๋‹ค.

4. UIButton์— ์žˆ๋Š” setImageํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด ์ด์ „์— ํฌ๊ธฐ๋ฅผ ์กฐ์ •ํ•œ ์ด๋ฏธ์ง€๋ฅผ ๊ฐ€์ ธ์™€์ค€๋‹ค.

 

์ด๋ ‡๊ฒŒ ํ•˜๋ฉด, UIButton ์•ˆ์— ์›ํ•˜๋Š” ์ด๋ฏธ์ง€๋ฅผ ๊ฐ€์ ธ์˜ค๊ณ , ๊ทธ ์ด๋ฏธ์ง€ ํฌ๊ธฐ๋ฅผ ๋งˆ์Œ๋Œ€๋กœ ์กฐ์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

 

728x90
๋ฐ˜์‘ํ˜•

+ Recent posts