2012-05-03 78 views
0

我有圓角的矩形UIButton,並希望爲它添加陰影,但是當我設置背景圖像陰影不可見時,我認爲背景覆蓋了陰影。沒有背景圖像陰影是可見自定義UIButton的影子

customBtn=[UIButton buttonWithType:UIButtonTypeRoundedRect]; 
    customBtn.frame=CGRectMake(customBtn.frame.origin.x, customBtn.frame.origin.y, 30, 30); 
    [customBtn setImage:[UIImage imageNamed:@"icon.png"] forState:UIControlStateNormal]; 
    [customBtn setBackgroundImage:[[UIImage imageNamed:@"bg.png"] stretchableImageWithLeftCapWidth:0 topCapHeight:0] forState:UIControlStateNormal]; 
    customBtn.layer.cornerRadius=9; 

customBtn.layer.shadowColor = [UIColor redColor].CGColor; 
    customBtn.layer.shadowOpacity = 1.0; 
    customBtn.layer.shadowRadius = 1; 
    customBtn.layer.shadowOffset = CGSizeMake(2.0f, 2.0f); 
customBtn.clipsToBounds=YES; 
+1

嘗試刪除clipToBounds = YES(或將其設置爲NO) – giorashc

回答

1

由於對UIButton內部結構,最好的辦法是建立一個可拉伸的背景圖像,其中包括陰影。

UIImage *bgWithShadow = [[UIImage imageNamed: @"bg.png"] 
          stretchableImageWithLeftCapWidth: 10 
               topCapHeight: 0]; 
[customBtn setBackgroundImage: bgWithShadow 
        forState: UIControlStateNormal]; 

本示例假設bg.png是包含陰影的21像素寬的圖像。基本上,你不需要做其他任何事情,比如訪問按鈕的圖層或者改變它的clipsToBounds屬性。請參閱this question以瞭解可拉伸圖像是什麼(帶圖片!)。

請注意,stretchableImageWithLeftCapWidth:topCapHeight:正在被棄用,以支持resizableImageWithCapInsets: