通过选择另一个UIImage的一部分进行UIImage
我有一个UIImage和一个CGPoint,告诉我应该在什么方向移动它来创建另一个图像。 背景可以是任何东西。
给出最初的UIImage如何创建新的? 这样做最有效的方法是什么?
这是我正在做的事情:
int originalWidth = image.size.width; int originalHeight = image.size.height; float xDifference = [[coords objectAtIndex:0] floatValue]; float yDifference = [[coords objectAtIndex:1] floatValue]; UIView *tempView = [[UIView alloc] initWithFrame:CGRectMake(0, 240, originalWidth, originalHeight)]; UIImageView *imageView = [[UIImageView alloc] initWithImage:image]; imageView.contentMode = UIViewContentModeTopLeft; CGRect imageFrame = imageView.frame; imageFrame.origin.x = xDifference; imageFrame.origin.y = -yDifference; imageView.frame = imageFrame; UIGraphicsBeginImageContext(tempView.bounds.size); [tempView.layer renderInContext:UIGraphicsGetCurrentContext()]; UIImage *finalImage = UIGraphicsGetImageFromCurrentImageContext(); UIGraphicsEndImageContext();
有更优化的版本吗?
您可以使用CGImageCreateWithImageInRect() 。 您可以UIImage
具有相同属性的 UIImage
获取CGImage
。
基本上你最终要做的是将遮罩应用于现有图像以提取所需的部分。 像这样 –
myImageArea = CGRectMake(xOrigin, yOrigin, myWidth, myHeight);//newImage mySubimage = CGImageCreateWithImageInRect(oldImage, myImageArea); myRect = CGRectMake(0, 0, myWidth*2, myHeight*2); CGContextDrawImage(context, myRect, mySubimage);
这篇文章很好地介绍了如何使用这个属性。