堆叠视图......需要进行代码审查

时间:2011-11-14 20:33:05

标签: objective-c uiview

问题:

  1. 在现有UIView之上,加载背景图片
  2. 从卡片组图片(大图)中剪下1张卡片(大图片的一部分)和
  3. 将该卡放在背景图像的顶部
  4. 以下代码有效。它完全符合我的需要。我问你但是..

    1. 我做得对吗?这是这样做的吗?
    2. 我真的需要使用的所有步骤吗?我有一种强烈的怀疑,我把它变得更复杂,然后才需要
    3. 感谢您的时间

      // Define overall UIView area and create a view
      UIView *background = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 460)];
      
      // Gain access to background image
      UIImage *backgroundImage = [UIImage imageNamed:@"green_background.jpg"]; 
      
      // Put background image on top of a 
      UIImageView *myImageView = [[UIImageView alloc] initWithImage:backgroundImage];
      
      // So now we have the view of some size with some image bahind it
      [background addSubview:myImageView];    
      
      
      // #####################################################################
      
      CGRect positionOnParentView = CGRectMake(40, 40, 50, 130);
      
      CGImageRef bigImage = [UIImage imageNamed:@"cards.png"].CGImage;    
      CGImageRef partOfABigImage = CGImageCreateWithImageInRect(bigImage, CGRectMake(0, 0, 200, 50));
      
      // get an image to be displayed
      UIImage *partOfImage = [UIImage imageWithCGImage:partOfABigImage];
      
      // Put it on it's onw view
      UIImageView *cardImage = [[UIImageView alloc] initWithImage:partOfImage];
      
      // create a UIview and add image 
      UIView *card = [[UIView alloc] initWithFrame:positionOnParentView];
      [card addSubview:cardImage];
      
      [background addSubview:card];
      
      [[self view] addSubview:background];
      

2 个答案:

答案 0 :(得分:1)

有几件事:

  1. 也许您刚刚没有包含发布声明,但请确保您正在发布您呼叫alloc的项目。你也可以自动发布它们。例如,

    UIView * background = [[[UIView alloc] initWithFrame:CGRectMake(0,0,320,460)] autorelease];

  2. 是的,你做得对,你真正减少你在这里的代码量的唯一方法是给每张卡片自己的图像,这样你就不必在大图像中裁剪。

答案 1 :(得分:1)

您正在创建此视图层次结构:

UIView (self.view)
  UIView (background)
    UIImageView (backgroundImage - backgroundImage)
    UIView (card)
      UIImageView (cardImage - partOfABigImage)

UIImageView可以有子视图。那么你需要所有这些中间观点吗?这个更简单的层次结构是否足够?

UIImageView (self.view - backgroundImage)
  UIImageView (cardImage - partOfABigImage)