合并多个图像视图

时间:2014-05-02 04:15:27

标签: ios uiimageview

原谅我如果我的问题太愚蠢,我是iOS开发的新手。

我有5张图片浏览量。每个imageview都有不同的背景颜色。

点击按钮我想生成1张图像,其中包含所有5张图像。含义(1种图像,5种颜色)。有人能告诉我如何实现这个目标吗?

我的故事板看起来与附图相似: enter image description here

1 个答案:

答案 0 :(得分:1)

以下方法适用于高度相同的图像,当我有时间时,我会为不同高度的图像添加选项。 (有关更多信息,请阅读下面的方法文档。)

该方法被设计为UIImage的类方法,它保留在一个类别中。

您可以将其称为

self.generatedImageView.image = [UIImage imageByAppendingImagesSideBySide:@[image1, image2, image3, image4, image5]];

/**
 *  Append images side-by-side. This method does not yet support height adjustments (like vertical align), instead images are aligned at the top.
 *  Example:
 *  Pic1 and Pic2 have both the same width and height.
 *  Pic3 has a larger width (which is fully supported).
 *  Pic4 has a larger height (which is **not** supported (yet)). That means that you cannot align the images as you want - they are aligned at the top.
 *  @code
 *  _______________________________________________________________
 *  |           |           |                 |                   |
 *  |           |           |                 |                   |
 *  |   Pic 1   |   Pic 2   |      Pic 3      |                   |
 *  |           |           |                 |                   |
 *  |___________|___________|_________________|        Pic4       |
 *  |                                         |                   |
 *  |                                         |                   |
 *  |                  Empty                  |                   |
 *  |                                         |                   |
 *  |_________________________________________|___________________|
 *
 *  @endcode
 *  @param images An array of UIImages.
 *
 *  @return An image with a width of the sum of all images' widths and a height of the largest image's height.
 */
+ (UIImage *)imageByAppendingImagesSideBySide:(NSArray *)images {
    // Set initial width to zero (we add it step-by-step in the for loop beneath, and height to the first images height, in the for loop we will figure out the image with the largest height.
    CGSize size = CGSizeMake(0, ((UIImage *)[images firstObject]).size.height);
    for (UIImage *image in images) {
        if ([image isKindOfClass:[UIImage class]]) {
            size.width = size.width + image.size.width;
            if (image.size.height > size.height) {
                size.height = image.size.height;
            }
        }
    }
    UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]);
    CGPoint currentRightMostPoint = CGPointZero;
    for (UIImage *image in images) {
        if ([image isKindOfClass:[UIImage class]]) {
            [image drawAtPoint:currentRightMostPoint];
            currentRightMostPoint = CGPointMake(currentRightMostPoint.x + image.size.width, currentRightMostPoint.y);
        }
    }
    UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return finalImage;
}