2011-11-14 45 views
0

問題:堆疊視圖...代碼審查所需

  1. 在現有的UIView的頂部,加載背景圖像
  2. 從一疊卡片圖像(大圖),剪卡1張(的一部分一個大的圖像),並且卡上的背景圖像的頂部

下面的代碼工作

  • 廣場。它正是我所需要的。我問你,雖然..

    1. 我在做對吧?它是這樣完成的嗎?
    2. 我用過的所有步驟真的需要嗎?我有一個強烈的懷疑我變得更加複雜,那麼它需要

    謝謝您的時間

    // 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]; 
    
  • 回答

    1

    你創建這個視圖層次:

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

    一個UIImageView可以有子視圖。那麼你需要所有這些中間視圖嗎?這個更簡單的層次結構是否足夠?

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

    幾件事情:

    1. 也許你只是沒」包括你的發佈聲明,但要確保你正在發佈你呼叫alloc的項目。你也可以自動釋放它們。例如,

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

    2. 是的,你做的是對的,真正減少代碼量的唯一方法就是讓每張卡都有自己的圖像,這樣你就不必在大圖像中裁剪。

    +0

    你可能想看看自動引用計數(ARC),所以你不需要發佈的東西;) – Faser