Add a shadow to the rounded corner Image

Source: Internet
Author: User

It is easy to display the UIView rounded corner. Only three lines of code are required.
CALayer * layer = [avatarImageView layer];
[Layer setMasksToBounds: YES];
[Layer setCornerRadius: 9.0];
 
However, if you add a shadow to a rounded view, the traditional method of adding a shadow is not feasible,
The traditional method is:
AvatarImageView. layer. shadowColor = [UIColor blackColor]. CGColor;
AvatarImageView. layer. shadowOffset = CGSizeMake (0, 1 );
AvatarImageView. layer. shadowOpacity = 1;
 
Because setMasksToBounds indicates that the content outside the frame is reduced, only the content in the frame can be displayed. Since the shadow added by this method is outside the frame, it is dropped.
The traditional method does not work, so we can put the avatarImageView of the rounded corner into a UIView with the same size as it, so that the view has a shadow, and the effect looks the same.
CGRect rect;
Rect = CGRectMake (0, 0, 48, 48 );
AvatarImageView = [[UIImageView alloc] initWithFrame: rect];
AvatarImageView. image = [UIImage imageNamed: @ "test.png"];
 
// Round the corners
CALayer * layer = [avatarImageView layer];
[Layer setMasksToBounds: YES];
[Layer setCornerRadius: 9.0];
 
// Add a shadow by wrapping the avatar into a container
UIView * shadow = [[UIView alloc] initWithFrame: rect];
AvatarImageView. frame = CGRectMake (0, 0, rect. size. width, rect. size. height );
 
// Setup shadow layer and corner
Shadow. layer. shadowColor = [UIColor grayColor]. CGColor;
Shadow. layer. shadowOffset = CGSizeMake (0, 1 );
Shadow. layer. shadowOpacity = 1;
Shadow. layer. shadowRadius = 9.0;
Shadow. layers. cornerRadius = 9.0;
Shadow. clipsToBounds = NO;
 
// Combine the views
[Shadow addSubview: avatarImageView];

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.