在iOS中将图像叠加在另一个图像上

时间:2011-09-05 21:47:48

标签: ios objective-c image

我正在iOS应用中显示来自youtube的缩略图。点击后,将转到youtube。

我需要一种将播放按钮覆盖到这些图像上的方法。这可能是最直接的方式吗?

此外,图像被远程加载到桌面上,因此性能是一个重要的考虑因素

4 个答案:

答案 0 :(得分:65)

如果您关心表滚动性能,请检索缩略图并在其上绘制播放按钮。

+(UIImage*) drawImage:(UIImage*) fgImage
              inImage:(UIImage*) bgImage
              atPoint:(CGPoint)  point
{
    UIGraphicsBeginImageContextWithOptions(bgImage.size, FALSE, 0.0);
    [bgImage drawInRect:CGRectMake( 0, 0, bgImage.size.width, bgImage.size.height)];
    [fgImage drawInRect:CGRectMake( point.x, point.y, fgImage.size.width, fgImage.size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return newImage;
}

答案 1 :(得分:5)

Swift 2.2版本

  static func drawImage(image foreGroundImage:UIImage, inImage backgroundImage:UIImage, atPoint point:CGPoint) -> UIImage{
    UIGraphicsBeginImageContextWithOptions(backgroundImage.size, false, 0.0)
    backgroundImage.drawInRect(CGRectMake(0, 0, backgroundImage.size.width, backgroundImage.size.height))
    foreGroundImage .drawInRect(CGRectMake(point.x, point.y, foreGroundImage.size.width, foreGroundImage.size.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage
  }

答案 2 :(得分:4)

这就是我所做的。 cameraImg是我从相机获取的图像,其他三个图像是我在相机上显示的静态图像。在这种情况下,size定义了我们将要开始的上下文的大小。图像在DrawInRect方法定义的矩形中绘制。确保结束上下文并完成。

UIImage *cameraImg = image;

UIImage *leftImg = [UIImage imageNamed:@"apple.jpeg"];

UIImage *rightImg = [UIImage imageNamed:@"Cloud.png"];

UIImage *middleImg = [UIImage imageNamed:@"mario.jpeg"];

CGSize size = CGSizeMake(cameraImg.size.width, cameraImg.size.height);

UIGraphicsBeginImageContext(size);

[cameraImg drawInRect:CGRectMake(0, 0, self.view.window.frame.size.width, self.view.window.frame.size.height)];

[leftImg drawInRect:CGRectMake(x, y, width, height)];

[rightImg drawInRect:CGRectMake(x, y, width, height)];

[middleImg drawInRect:CGRectMake(x, y, width, height)];

UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext();

UIGraphicsEndImageContext();

UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0,finalImage.size.width, finalImage.size.height)];

imageView.image = finalImage;

[self.view addSubview:imageView];

答案 3 :(得分:2)

Swift 3.x

func drawImage(image foreGroundImage:UIImage, inImage backgroundImage:UIImage, atPoint point:CGPoint) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(backgroundImage.size, false, 0.0)
    backgroundImage.draw(in: CGRect.init(x: 0, y: 0, width: backgroundImage.size.width, height: backgroundImage.size.height))
    foreGroundImage.draw(in: CGRect.init(x: point.x, y: point.y, width: foreGroundImage.size.width, height: foreGroundImage.size.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return newImage!
}