代码之家  ›  专栏  ›  技术社区  ›  Vishwanath Deshmukh

如何在iOS中创建带阴影和子视图的UIimageView

  •  1
  • Vishwanath Deshmukh  · 技术社区  · 6 年前

    如何使用objective C创建具有阴影效果的UIImageView及其子视图(小图像图标和标签)。图像可能如下所示:

    White image with shadow and small image and label as subview on top of it

     self.view.backgroundColor = [UIColor whiteColor];
    
    UIImageView* image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"profImg.jpeg"]];
     image.frame = CGRectMake(40, 200, 150, 100);
     image.layer.cornerRadius = 9; 
    image.layer.shouldRasterize = YES;
    image.layer.masksToBounds = YES;
    
    // make new layer to contain shadow and masked image
    CALayer* containerLayer = [CALayer layer];
    containerLayer.shadowColor = [UIColor blackColor].CGColor;
    containerLayer.shadowRadius = 9.f;
    containerLayer.shadowOffset = CGSizeMake(1.f, 2.f);
    containerLayer.shadowOpacity = .6f;
    
    // add masked image layer into container layer so that it's shadowed
    [containerLayer addSublayer:image.layer];
    
    // add container including masked image and shadow into view
    [self.view.layer addSublayer:containerLayer];
    

    我无法在该图像上添加子图像和标签。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Nitish    6 年前

    UIImageView 边框:

    imageView.layer.borderWidth = 5  
    imageView.layer.borderColor = UIColor.gray.cgColor     // Set as per requirement 
    

    子视图 :

    实际上,不需要将标签(Title)作为imageView的子视图。将其保持在与imageView相同的级别。

    let labelTitle = UILabel(frame: CGRect(x: imageView.frame.origin.x, y: (imageView.frame.origin.y + imageView.frame.size.height - 30), width: imageView.frame.size.width, height: 20))  
    labelTitle.text = "Title"  
    labelTitle.backgroundColor = UIColor.gray      // Keep it same as imageView's border color  
    self.view.addSubView(labelTitle)   // replace self.view by imageView's parent  
    self.view.bringSubview(toFront: labelTitle)
    
        2
  •  0
  •   Aleem    6 年前
    func shadowEffectImageView() {
    
        imageView.layer.shadowColor = UIColor.purple.cgColor
        imageView.layer.shadowOffset = CGSize(width: 0, height: 1)
        imageView.layer.shadowOpacity = 1
        imageView.layer.shadowRadius = 1.0
        imageView.clipsToBounds = false
    }