現在,我的代碼將一個藍色框保存在紅色框中。我需要將藍框的大小縮小50%。因此,所有藍色框都有紅色邊框。我有一個擴展文件應該能夠縮小圖像,但我不知道把它放到我的代碼中。如何調整打印圖像的大小(swift3)
extension UIImage {
func resized(withPercentage percentage: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: size.width * percentage, height: size.height * percentage)
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}
func resized(toWidth width: CGFloat) -> UIImage? {
let canvasSize = CGSize(width: width, height: CGFloat(ceil(width/size.width * size.height)))
UIGraphicsBeginImageContextWithOptions(canvasSize, false, scale)
defer { UIGraphicsEndImageContext() }
draw(in: CGRect(origin: .zero, size: canvasSize))
return UIGraphicsGetImageFromCurrentImageContext()
}}
import UIKit
class ViewController: UIViewController {
var image1 = UIImage(named: "red")
var image2 = UIImage(named: "blue")
func cropImageIntoQuarterSquare(image: UIImage) -> UIImage? {
let originalImageSize: CGSize = image.size
let smallImageSize = CGSize(width: (originalImageSize.width + 40), height: (originalImageSize.height + 40))
UIGraphicsBeginImageContext(smallImageSize)
image.draw(at: CGPoint.zero)
let imageResult = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return imageResult
}
override func viewDidLoad() {
super.viewDidLoad()}
func saveImage(image1: UIImage, image2: UIImage) -> UIImage? {
let size1 = image1.size
let size2 = image2.size
let origin = CGPoint(x: size1.width - size2.width, y: size1.height - size2.height)
UIGraphicsBeginImageContext(size1)
image1.draw(in: CGRect(origin: CGPoint.zero, size: size1))
image2.draw(in: CGRect(origin: origin, size: size2))
let combinedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return combinedImage
}
func image(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
if let error = error {
// we got back an error!
let ac = UIAlertController(title: "Save error", message: error.localizedDescription, preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
} else {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .alert)
ac.addAction(UIAlertAction(title: "OK", style: .default))
present(ac, animated: true)
}
}
@IBAction func d(_ sender: Any) {
guard let croppedImage = cropImageIntoQuarterSquare(image: image2!),
let combinedImage = saveImage(image1: image1!, image2: croppedImage) else {
// handle the error
return
}
UIImageWriteToSavedPhotosAlbum(combinedImage, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil)
}}
我的答案沒有解決您的問題? –