العمل مع الصور في Swift (iOS/macOS)
في هذه المقالة، سنستعرض الأساليب والأدوات الأساسية للعمل مع الصور في نظام Apple البيئي. ستتعلم كيفية تحميل الصور وعرضها ومعالجتها وحفظها باستخدام أطر Swift المدمجة لنظامي iOS و macOS. ستكون المادة مفيدة لكل من المبتدئين والمطورين ذوي الخبرة.
الأطر الرئيسية للعمل مع الصور
توجد عدة أطر رئيسية في Swift للعمل مع الرسوميات:
- UIKit (iOS) —
UIImage,UIImageView - AppKit (macOS) —
NSImage,NSImageView - Core Image — الفلاتر والمعالجة
- Core Graphics — الرسم منخفض المستوى
- Metal — تسريع GPU للعمليات المعقدة
- SwiftUI — واجهة تصريحية مع
Image
تحميل الصور وعرضها
دعنا نستعرض أمثلة أساسية لكلا النظامين.
iOS (UIKit)
import UIKit
// التحميل من الأصولlet image = UIImage(named: "example")
// التحميل من ملفif let path = Bundle.main.path(forResource: "photo", ofType: "jpg") { let imageFromFile = UIImage(contentsOfFile: path)}
// العرض في UIImageViewlet imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200))imageView.image = imageimageView.contentMode = .scaleAspectFitmacOS (AppKit)
import AppKit
// التحميل من الأصولlet image = NSImage(named: "example")
// التحميل من ملفif let path = Bundle.main.path(forResource: "photo", ofType: "jpg") { let imageFromFile = NSImage(contentsOfFile: path)}
// العرض في NSImageViewlet imageView = NSImageView(frame: NSRect(x: 0, y: 0, width: 200, height: 200))imageView.image = imageimageView.imageScaling = .scaleProportionallyUpOrDownSwiftUI (عبر المنصات)
import SwiftUI
struct ContentView: View { var body: some View { Image("example") .resizable() .aspectRatio(contentMode: .fit) .frame(width: 200, height: 200) }}معالجة الصور باستخدام Core Image
يوفر Core Image أكثر من 200 فلتر مدمج لمعالجة الصور. إليك مثال لتطبيق تأثير السيبيا:
import CoreImage
func applySepiaFilter(to image: UIImage) -> UIImage? { guard let ciImage = CIImage(image: image) else { return nil } let filter = CIFilter(name: "CISepiaTone") filter?.setValue(ciImage, forKey: kCIInputImageKey) filter?.setValue(0.8, forKey: kCIInputIntensityKey) guard let outputImage = filter?.outputImage else { return nil } let context = CIContext() guard let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else { return nil } return UIImage(cgImage: cgImage)}تغيير الحجم والقص
غالبًا ما يكون من الضروري تغيير حجم الصورة أو قصها من المنتصف:
extension UIImage { func resized(to targetSize: CGSize) -> UIImage { let renderer = UIGraphicsImageRenderer(size: targetSize) return renderer.image { _ in self.draw(in: CGRect(origin: .zero, size: targetSize)) } } func croppedToSquare() -> UIImage { let side = min(size.width, size.height) let x = (size.width - side) / 2 let y = (size.height - side) / 2 let cropRect = CGRect(x: x, y: y, width: side, height: side) guard let cgImage = cgImage?.cropping(to: cropRect) else { return self } return UIImage(cgImage: cgImage) }}حفظ الصور
دعنا نستعرض كيفية حفظ الصورة في المعرض أو في ملف: