2012-06-14 2 views
14

이 질문에 대해 유감스럽게 생각하지만 여기 S.O.에서 많은 스레드를 검색했습니다. 나는 아무것도 발견하지 못했습니다.UIImage에서 중심 사각형을 자르는 방법?

질문 : UIImage에서 중심 사각형을 자르는 방법은 무엇입니까?

나는 아래 코드를 시도했지만 성공하지는 못했다. 자르기가 발생하지만 왼쪽 위 모서리에 있습니다.

-(UIImage*)imageCrop:(UIImage*)original 
{ 
    UIImage *ret = nil; 

    // This calculates the crop area. 

    float originalWidth = original.size.width; 
    float originalHeight = original.size.height; 

    float edge = fminf(originalWidth, originalHeight); 

    float posX = (originalWidth - edge)/2.0f; 
    float posY = (originalHeight - edge)/2.0f; 


    CGRect cropSquare = CGRectMake(posX, posY, 
            edge, edge); 


    // This performs the image cropping. 

    CGImageRef imageRef = CGImageCreateWithImageInRect([original CGImage], cropSquare); 

    ret = [UIImage imageWithCGImage:imageRef 
           scale:original.scale 
         orientation:original.imageOrientation]; 

    CGImageRelease(imageRef); 

    return ret; 
} 

답변

15

내가 사진을 캡처 한 후이 '작물'을 사용하고 더 많은 정보를 추가.

몇 가지 테스트를 마친 결과 나는 효과가있는 것을 발견했습니다.

// If orientation indicates a change to portrait. 
if(original.imageOrientation == UIImageOrientationLeft || 
    original.imageOrientation == UIImageOrientationRight) 
{ 
    cropSquare = CGRectMake(posY, posX, 
          edge, edge); 

} 
else 
{ 
    cropSquare = CGRectMake(posX, posY, 
          edge, edge); 
} 
관련 문제