UIView透明效果

在iOS开发中,要创建一个透明的UIView但保持其上的图片不透明,应将背景颜色设为clearColor而不是设置UIView的alpha值。本文记录了一种实现方法:创建一个UIView,设置其背景为clearColor,然后添加UIImageView显示图片,再添加UIButton作为子视图。通过这种方法,即使UIView透明,按钮仍然可以正常响应点击。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在做UIView的透明效果时,想让UIView上的图片不透明,那么就只能设置backgroundcolor = [uicolor clearcolor],     

切记不可以设置 alpha = ...;     因为设置alpha的话就相当于把UIView下的subviews也都设置成透明的了


下面记录下我的这种效果的实现方法, 以免过几天就忘了,我的烂记性:


分别是横条带透明度的长条栏,四个button及四个点击后的变蓝色的图,实现方法:

customToolbar = [[UIViewalloc]initWithFrame:CGRectMake(0,367,320,49)];

    //        customToolbar.alpha = 0.5;    //切记这个地方不要设置alpha

    customToolbar.backgroundColor = [UIColorclearColor];

    

    UIImageView *imgview = [[UIImageViewalloc]initWithImage:[UIImageimageNamed:@"blackground@2x.png"]];

    imgview.frame = CGRectMake(0,0,320, 49);

    [customToolbar addSubview:imgview];

(注意:后边的四个button再定义后,用 customToolbar 直接 addsubview可以实现点击,而用 imgview addsubview的话却不可以 ,不知道 为什么)

UIButton *cusbutton1 = [UIButton buttonWithType:UIButtonTypeCustom];

    cusbutton1.frame = CGRectMake(20, 5, 40, 39);

    cusbutton1.tag = 1;

    [cusbutton1 addTarget:self action:@selector(press:) forControlEvents:UIControlEventTouchUpInside];

    [cusbutton1 setImage:[UIImage imageNamed:@"refresh.png"] forState:UIControlStateNormal];

    [cusbutton1 setImage:[UIImage imageNamed:@"refresh_click.png"] forState:UIControlStateSelected];

    

    //        [cusbutton1 setBackgroundImage:[UIImage imageNamed:@"enjoy.png"] forState:UIControlStateNormal];

    //        [cusbutton1 setBackgroundImage:[UIImage imageNamed:@"butImg.png"] forState:UIControlStateSelected];

    [customToolbar addSubview:cusbutton1];   //chenyy 注意这个地方,若用[imgview addsubview:cusbutton1]却不行





右下角那个小图标的实现代码:(butImg.png即是让美工就是做好的带透明度的图

UIButton *rightButton = [UIButtonbuttonWithType:UIButtonTypeRoundedRect];

    rightButton.frame = CGRectMake(270,350, 35, 35);

    rightButton.backgroundColor = [UIColorclearColor];

//    rightButton.alpha = 0.5;

    [rightButton addTarget:selfaction:@selector(clickRightButton)forControlEvents:UIControlEventTouchUpInside];

    [rightButton setBackgroundImage:[UIImageimageNamed:@"butImg.png"]forState:UIControlStateNormal];

    [self.view addSubview:rightButton];



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值