使用Swift和UIKit创建图片编辑App
创作时间:
作者:
@小白创作中心
使用Swift和UIKit创建图片编辑App
引用
5
来源
1.
https://www.kodeco.com/18895088-uicollectionview-tutorial-getting-started
2.
https://developer.apple.com/documentation/coreimage/processing_an_image_using_built-in_filters
3.
https://developer.apple.com/tutorials/app-dev-training/adopting-collection-views
4.
https://www.kodeco.com/30195423-core-image-tutorial-getting-started
5.
https://www.hackingwithswift.com/books/ios-swiftui/basic-image-filtering-using-core-image
本篇文章将带你使用Swift和UIKit通过纯代码方式创建一个简单的图片编辑应用程序。这个应用将实现以下功能:
- 界面分为上下两部分:上面显示一张预设的图片,下面是一个可以左右滑动的视图,用于展示不同滤镜效果的缩略图。
- 点击任一缩略图后,上方的图片将应用对应的滤镜效果。
项目结构
首先,我们需要创建一个UIViewController作为主界面,包含一个UIImageView显示原图,以及一个UICollectionView来展示滤镜缩略图。
import UIKit
import CoreImage
class ImageEditorViewController: UIViewController {
let imageView = UIImageView()
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout())
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
func setupUI() {
view.addSubview(imageView)
imageView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
imageView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
imageView.heightAnchor.constraint(equalToConstant: 300)
])
imageView.contentMode = .scaleAspectFit
imageView.image = UIImage(named: "your-image-name")
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(FilterCollectionViewCell.self, forCellWithReuseIdentifier: "FilterCell")
collectionView.backgroundColor = .white
view.addSubview(collectionView)
collectionView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: imageView.bottomAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.safeAreaLayoutGuide.bottomAnchor)
])
}
}
实现滤镜功能
接下来,我们需要使用Core Image框架来实现滤镜功能。首先定义一组常用的滤镜:
enum FilterType: String {
case sepiaTone = "CISepiaTone"
case photoEffectInstant = "CIPhotoEffectInstant"
case photoEffectNoir = "CIPhotoEffectNoir"
case photoEffectChrome = "CIPhotoEffectChrome"
case colorInvert = "CIColorInvert"
case colorMonochrome = "CIColorMonochrome"
case colorControls = "CIColorControls"
case exposureAdjust = "CIExposureAdjust"
case gammaAdjust = "CIGammaAdjust"
case hueAdjust = "CIHueAdjust"
case temperatureAndTint = "CITemperatureAndTint"
case vibrance = "CIVibrance"
case whitePointAdjust = "CIWhitePointAdjust"
}
然后,我们需要一个方法来应用滤镜:
func applyFilter(_ filterType: FilterType, to image: UIImage) -> UIImage? {
guard let ciImage = CIImage(image: image) else { return nil }
let context = CIContext()
let filter = CIFilter(name: filterType.rawValue)
filter?.setValue(ciImage, forKey: kCIInputImageKey)
if let outputImage = filter?.outputImage {
if let cgImage = context.createCGImage(outputImage, from: outputImage.extent) {
return UIImage(cgImage: cgImage)
}
}
return nil
}
处理用户交互
当用户点击collection view中的cell时,我们需要获取对应的滤镜并应用到原图上:
extension ImageEditorViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return FilterType.allCases.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "FilterCell", for: indexPath) as! FilterCollectionViewCell
let filterType = FilterType.allCases[indexPath.item]
cell.filterImageView.image = applyFilter(filterType, to: imageView.image!)
cell.filterLabel.text = filterType.rawValue
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let filterType = FilterType.allCases[indexPath.item]
imageView.image = applyFilter(filterType, to: imageView.image!)
}
}
性能优化
为了提高性能,我们需要在后台队列异步处理滤镜生成,并缓存已生成的缩略图:
var filterCache = [FilterType: UIImage]()
func applyFilter(_ filterType: FilterType, to image: UIImage) -> UIImage? {
if let cachedImage = filterCache[filterType] {
return cachedImage
}
DispatchQueue.global(qos: .userInitiated).async {
guard let ciImage = CIImage(image: image) else { return }
let context = CIContext()
let filter = CIFilter(name: filterType.rawValue)
filter?.setValue(ciImage, forKey: kCIInputImageKey)
if let outputImage = filter?.outputImage {
if let cgImage = context.createCGImage(outputImage, from: outputImage.extent) {
let filteredImage = UIImage(cgImage: cgImage)
DispatchQueue.main.async {
self.filterCache[filterType] = filteredImage
}
return filteredImage
}
}
}
return nil
}
最后
通过以上步骤,我们就完成了一个简单的图片编辑App。这个应用展示了如何使用Swift和UIKit创建自定义界面,并使用Core Image框架实现图片滤镜功能。你可以根据需要添加更多滤镜效果,或者优化用户界面和交互体验。
热门推荐
化妆品成分解析,了解了这些才是真正“护肤有道”
量子力学与宇宙力量的新视角:多元宇宙的奥秘
LIGO技术升级再创辉煌:从引力波探测到纳赫兹引力波突破
《河边有个好地方》:一部关于成长、友谊与教育的温情之作
2025春节美容新趋势:从美甲到接睫毛,年轻人的"过年三件套"大揭秘
阳朔8人团队游必打卡三大景点揭秘!
冲绳必吃美食16选:塔可饭、冲绳牛排、通堂拉面、石垣牛、阿古猪都超推!
济南九转大肠:舌尖上的历史传奇
自贡灯会:千年盐都的光影盛宴
自贡灯会璀璨启幕:中华彩灯大世界的光影盛宴
正确姿势,合理用眼:远离“小眼镜”的六个实用建议
扬州TS CD男娘:探寻性别身份与文化的交织
解决苹果手机网络问题的方法:一步步操作指南
米芾春联大法好!教你写出高逼格对子
春节倒计时!春联中的语言魔法大揭秘
00后用社交媒体玩转春联新花样
山鬼花钱:家居风水新宠
教你几招识别真假“山鬼花钱”
清代山鬼花钱:道教咒语的秘密与文化内涵
成都造币厂揭秘:八卦山鬼花钱的文化传承与艺术价值
二月份去大理的旅游攻略:2月大理旅游全攻略及适宜性分析
精神胜利法:科学应对胃疼的心理攻略
秋冬胃疼?苹果醋+生姜帮你搞定!
潍烟高铁开通运营,铺就区域繁荣的“康庄大道”
老年志愿者:社区温暖新力量
运动让老年生活更精彩:从身体到心理的全方位益处
中医药滋阴降火法在现代生活中的重要应用
秋冬打卡南京三大必拍景点
冬日南京必打卡:夫子庙、秦淮河与钟山风景区
南京深秋赏枫攻略:四大景点最佳打卡指南