본문 바로가기
프로그래밍/iOS

Cropping Images using Graphic Contexts

by 백룡화검 2012. 4. 25.

주제 : Core Graphics API 사용해 이미지를 자르고 늘리는 작업을 한다.


이미지 늘리기
다음은 1px을 가지는 이미지를 UIImage 클래스가 지원하는
stretchableImageWithLeftCapWidht:topCapHeight: 메서드를 이용해 이미지 뷰를 만드는 방법이다. 이와 같은 방법으로 패턴 이미지도 생성이 가능하고 간단하게 이미지를 변형이 가능하다.

UIImage *image = [[UIImage imageNamed:@"1px-blue-divider.png"] stretchableImageWithLeftCapWidth:0.0 topCapHeight:0.0];
    UIImageView *imageView = [[[UIImageView alloc] initWithImage:image] autorelease];
    imageView.frame = CGRectMake(0, 0, 300.0, image.size.height);
    [self.window addSubview:imageView];


버튼 이미지 늘리기
다음은 위에서 설명한 이미지 늘리기를 통해 rounded 버튼 이미지를 만드는 방법이다. CapWidth 값에 5.0를 준다는것은 좌, 우 5pixel의 값을 그대로 두고 가운데 값을 늘려버린다는 것이다. 이미지 가로 사이즈는 11pixel이 되겠다.

UIImage *buttonImage = [[UIImage imageNamed:@"button.png"] stretchableImageWithLeftCapWidth:5.0 topCapHeight:0.0];
    UIImageView *buttonImageView = [[[UIImageView alloc] initWithImage:buttonImage] autorelease];
    buttonImageView.frame = CGRectMake(0, 100, 300.0, buttonImage.size.height);


이미지 Cropping 처리 메서드
다음은 CoreGraphics API 를 직접 접근해 이미지를 자유자재로 자르는 방법이다. 위에 설명한 방법 보다 조금 복잡해 보이지만 퀴츠 2d에 대한 이해가 있다면 간단하다. drawInRect 메소드를 보면 CGRectMake를 통해 이미지를 Draw할 영역을 설정하는데 width를 설정하는 부분에 button의 가로 사이즈와 capWidth를 이용해 영역을 그리게 된다. 결과 값은 UIImage로 리턴하게 된다.

 -(UIImage*)image:(UIImage*)image withCap:(CapLocation)location capWidth:(NSUInteger)capWidth buttonWidth:(NSUInteger)buttonWidth
{
  UIGraphicsBeginImageContextWithOptions(CGSizeMake(buttonWidth, image.size.height), NO, 0.0);

  if (location == CapLeft)
    // To draw the left cap and not the right, we start at 0, and increase the width of the image by the cap width to push the right cap out of view
    [image drawInRect:CGRectMake(0, 0, buttonWidth + capWidth, image.size.height)];
  else if (location == CapRight)
    // To draw the right cap and not the left, we start at negative the cap width and increase the width of the image by the cap width to push the left cap out of view
    [image drawInRect:CGRectMake(0.0-capWidth, 0, buttonWidth + capWidth, image.size.height)];
  else if (location == CapMiddle)
    // To draw neither cap, we start at negative the cap width and increase the width of the image by both cap widths to push out both caps out of view
    [image drawInRect:CGRectMake(0.0-capWidth, 0, buttonWidth + (capWidth * 2), image.size.height)];

  UIImage* resultImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();

  return resultImage;
}



출처 : http://xajax.tistory.com/25