基本プロセス:
- CGContext
- クリア(OBJの-C)を使用して新しいUIImageの中心でRECT
CGContextClearRect(CGContextRef c, CGRect rect);
または(スウィフト).clear(_ rect: CGRect)
を取得
- ソリッドカラーUIImageを作成します。
- ここで新しいイメージの「透明RECT」へ
を元の画像を描画元であります十分、使用スウィフト:
func drawImageOnCanvas(_ useImage: UIImage, canvasSize: CGSize, canvasColor: UIColor) -> UIImage {
let rect = CGRect(origin: .zero, size: canvasSize)
UIGraphicsBeginImageContextWithOptions(rect.size, false, 0.0)
// fill the entire image
canvasColor.setFill()
UIRectFill(rect)
// calculate a Rect the size of the image to draw, centered in the canvas rect
let centeredImageRect = CGRect(x: (canvasSize.width - useImage.size.width)/2,
y: (canvasSize.height - useImage.size.height)/2,
width: useImage.size.width,
height: useImage.size.height)
// get a drawing context
let context = UIGraphicsGetCurrentContext();
// "cut" a transparent rectanlge in the middle of the "canvas" image
context?.clear(centeredImageRect)
// draw the image into that rect
useImage.draw(in: centeredImageRect)
// get the new "image in the center of a canvas image"
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
とこのようにそれを呼び出す:
if let img = UIImage(named: "myimage") {
let expandedSize = CGSize(width: img.size.width + 60, height: img.size.height + 60)
let imageOnBlueCanvas = drawImageOnCanvas(img, canvasSize: expandedSize, canvasColor: .blue)
let v = UIImageView(image: imageOnBlueCanvas)
view.addSubview(v)
}