我使用按照客觀C,對於任何圖像裁剪非transperant矩形。檢查它是否有幫助
@implementation UIImage (cropTransperant)
- (UIImage *) CropimageByTrimmingTransparentPixels {
int rows = self.size.height;
int cols = self.size.width;
int bytesPerRow = cols*sizeof(uint8_t);
if (rows < 2 || cols < 2) {
return self;
}
uint8_t *bitmapData = calloc(rows*cols, sizeof(uint8_t));
CGContextRef contextRef = CGBitmapContextCreate(bitmapData, cols, rows, 8, bytesPerRow, NULL, kCGImageAlphaOnly);
CGImageRef cgImage = self.CGImage;
CGRect rect = CGRectMake(0, 0, cols, rows);
CGContextDrawImage(contextRef, rect, cgImage);
//get all non-transparent pixels in every row and every column
uint16_t *rowSum = calloc(rows, sizeof(uint16_t));
uint16_t *colSum = calloc(cols, sizeof(uint16_t));
//loop through all pixels
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++)
{
if (bitmapData[row*bytesPerRow + col]) { //when you get non transperant pixel
rowSum[row]++;
colSum[col]++;
}
}
}
UIEdgeInsets crop = UIEdgeInsetsMake(0, 0, 0, 0); //croprect, initialize with 0,0,0,
for (int i = 0; i<rows; i++) { //get top
if (rowSum[i] > 0) {
crop.top = i; break;
}
}
for (int i = rows; i >= 0; i--) { //get bottom
if (rowSum[i] > 0) {
crop.bottom = MAX(0, rows-i-1); break;
}
}
for (int i = 0; i<cols; i++) { //get left
if (colSum[i] > 0) {
crop.left = i; break;
}
}
for (int i = cols; i >= 0; i--) { //get right
if (colSum[i] > 0) {
crop.right = MAX(0, cols-i-1); break;
}
}
free(bitmapData);
free(colSum);
free(rowSum);
if (crop.top == 0 && crop.bottom == 0 && crop.left == 0 && crop.right == 0) {
return self;
}
else {
rect.origin.x += crop.left;
rect.origin.y += crop.top;
rect.size.width -= crop.left + crop.right;
rect.size.height -= crop.top + crop.bottom;
//crop image to calcualted rect
CGImageRef newImage = CGImageCreateWithImageInRect(cgImage, rect);
return [UIImage imageWithCGImage:newImage];
}
}
@end
不,請繼續前進並裁剪它。這很簡單,只需要調用一次'CGImageCreateWithImageInRect'。 – Rob
感謝您對@Rob的評論,你會介意分享一個關於如何實現這個的快速代碼片段嗎? – Aleksander
不需要編碼樣本Rob,我想通了。感謝指針! – Aleksander