How to combine two UIImages of difference size without altering their original aspect ratios?

后端 未结 4 1223
说谎
说谎 2021-01-26 10:29

My current method of combining UIImages come from this answer on SO, as well as this popular question on resizing UIImage with aspect ratio. My current issue is the following:<

4条回答
  •  说谎
    说谎 (楼主)
    2021-01-26 11:12

    • Support Portrait and Landscape both type of image
    • Drawing and other subviews can be merged in my case I'm adding label to draw
      {
    
        CGSize fullSize = getImageForEdit.size;
        CGSize sizeInView = AVMakeRectWithAspectRatioInsideRect(imgViewFake.image.size, imgViewFake.bounds).size;
        CGFloat orgScale = orgScale = fullSize.width/sizeInView.width;
        CGSize newSize = CGSizeMake(orgScale * img.image.size.width, orgScale * img.image.size.height);
        if(newSize.width <= fullSize.width && newSize.height <= fullSize.height){
            newSize = fullSize;
        }
        CGRect offsetRect;
        if (getImageForEdit.size.height > getImageForEdit.size.width){
            CGFloat scale = newSize.height/fullSize.height;
            CGFloat offset = (newSize.width - fullSize.width*scale)/2;
            offsetRect = CGRectMake(offset, 0, newSize.width-offset*2, newSize.height);
        }
        else{
            CGFloat scale = newSize.width/fullSize.width;
            CGFloat offset = (newSize.height - fullSize.height*scale)/2;
            offsetRect = CGRectMake(0, offset, newSize.width, newSize.height-offset*2);
        }
        UIGraphicsBeginImageContextWithOptions(newSize, NO, getImageForEdit.scale);
        [getImageForEdit drawAtPoint:offsetRect.origin];
        //        [img.image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
        CGFloat oldScale = img.contentScaleFactor;
        img.contentScaleFactor = getImageForEdit.scale;
        [img drawViewHierarchyInRect:CGRectMake(0, 0, newSize.width, newSize.height) afterScreenUpdates:YES];
        img.contentScaleFactor = oldScale;
        UIImage *combImage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        imageData = UIImageJPEGRepresentation(combImage, 1);
    }
    

提交回复
热议问题