2017-11-27 26 views
1

간단히 말해 작물 조작을 "되돌리기"를 원합니다. 자르기에서는 rect를 선택하고 지정된 rect로 이미지를 자릅니다. 내 경우에는 반대의 일을 할 필요가있다 - 이미지 주위에 빈 공간을 추가하고 색으로 채우기. 참고 - 이미지는 투명한 배경을 가질 수 있으므로 다른 이미지 위에 하나의 이미지 만 그릴 수는 없습니다.UIImage의 캔버스 크기를 조정하고 빈 곳을 채우시겠습니까?

내가 이미 가지고있는 모든 입력 데이터 (직사각형과 이미지). 이 작업을 해결하는 방법?

답변

0

기본 과정 :

  1. 단색있는 UIImage
  2. 만들기 CGContext
  3. 지우기 OBJ (-C) CGContextClearRect(CGContextRef c, CGRect rect); 또는 (스위프트) .clear(_ rect: CGRect)와 새로운있는 UIImage의 중앙에 RECT 받기
  4. 새로운 이미지 여기

의 "투명 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) 

    }