使用多个可伸缩图像构建UIImage

Chr*_*ris 4 drawing core-graphics objective-c uiimage ios

我有3张图片,一张左帽,右帽和中心.也许使用CGImageRefs(?),有没有办法建立一个位图,基于一个CGRect将中心部分置于某个容器中心,拉伸左帽直到它到达中心部分,然后相同的右边然后产生一个UIImage

Pfi*_*itz 6

好吧,我按照承诺查看了它.这是一个解决方案:

基本理念

  • 取左帽,UIImage右侧伸展
  • 用箭头"粘"它 UIImage
  • 现在用右侧盖子将其粘合在一起,左侧拉伸

这是一个小图,我认为它可以说

  ______ ........    ________      .........___________
 {______|........|  | arrow  |    |.........|__________)
left cap|lc flex     --------      rc flex  | right cap
Run Code Online (Sandbox Code Playgroud)

代码

// get the images from disk
UIImage *leftCap = [UIImage imageNamed:@"leftCap.png"];
UIImage *arrow = [UIImage imageNamed:@"arrow.png"];
UIImage *rightCap = [UIImage imageNamed:@"rightCap"];

// stretch left and right cap
// calculate the edge insets beforehand !

UIImage *leftCapStretched = [leftCap resizableImageWithCapInsets:UIEdgeInsetsMake(topInset, leftInset, bottomInset, rightInset)];
UIImage *rightCapStretched = [rightCap resizableImageWithCapInsets:UIEdgeInsetsMake(topInset, leftInset, bottomInset, rightInset)];

CGFloat widthOfAllImages = leftCapStretched.size.width + arrow.size.width + rightCapStretched.size.width;

// build the actual glued image

UIGraphicsBeginImageContextWithOptions(CGSizeMake(widthOfAllImages, arrow.size.height), NO, 0);
[leftCapStretched drawAtPoint:CGPointMake(0, 0)];
[arrow drawAtPoint:CGPointMake(leftCap.size.width, 0)];
[rightCapStretched drawAtPoint:CGPointMake(leftCap.size.width + arrow.size.width, 0)];
UIImage* im = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext();

// now you should have a ready to use UIImage ;)
Run Code Online (Sandbox Code Playgroud)

替代方案

灵感来自乔纳森·普拉克茨(Jonathan Plaketts)的回答,应该只是UIImageViews如上所述,并且如上所述延伸UIImages.