IOS _ Custom Glass Effect

Source: Internet
Author: User

IOS _ Custom Glass Effect

Finally:

 

 

 

 

Key code:

 

UIImage classification code

 

/// UIImage + BlurGlass. h // handsome guy _ buy /// Created by beyond on 14-8-30. // Copyright (c) 2014 com. beyond. all rights reserved. // category of glass wool effect UIImage # import
 
  
@ Interface UIImage (BlurGlass)/* 1. White, parameter: transparency 0 ~ 1, 0 is white, 1 is dark gray radius: 30 by default, the larger the recommended value 3 radius value, the blurrier the smaller the value, the clearer the color saturation (concentration) factor: 0 is black and white, 9 is a thick color, 1 is the default color of 1.8 "color", English is called Saturation, that is, Saturation. Set the color-free black and white gray to 0 and the brightest to 9 s, which is roughly divided into ten stages, so that the values are consistent with the sensory intuition of people. */-(UIImage *) imgWithLightAlpha :( CGFloat) alpha radius :( CGFloat) radius colorSaturationFactor :( CGFloat) colorSaturationFactor; // 2. encapsulated-(UIImage *) imgWithBlur; @ end
 


 

 

/// UIImage + BlurGlass. m // handsome _ buy /// Created by beyond on 14-8-30. // Copyright (c) 2014 com. beyond. all rights reserved. // # import UIImage + BlurGlass. h # import @ implementation UIImage (BlurGlass)/* 1. white, parameter: transparency 0 ~ 1, 0 is white, 1 is dark gray radius: 30 by default, the larger the recommended value 3 radius value, the blurrier the smaller the value, the clearer the color saturation (concentration) factor: 0 is black and white, 9 is a thick color, 1 is the default color of 1.8 "color", English is called Saturation, that is, Saturation. Set the color-free black and white gray to 0 and the brightest to 9 s, which is roughly divided into ten stages, so that the values are consistent with the sensory intuition of people. */-(UIImage *) imgWithLightAlpha :( CGFloat) alpha radius :( CGFloat) radius colorSaturationFactor :( CGFloat) colorSaturationFactor {UIColor * tintColor = [UIColor colorWithWhite: 1.0 alpha: alpha]; return [self imgBluredWithRadius: radius tintColor: tintColor saturationDeltaFactor: colorSaturationFactor maskImage: nil];} // 2. encapsulated for external calls-(UIImage *) imgWithBlur {// call method 1 return [self imgWithLightAlpha: 0.1 radius: 3 colorSaturationFactor: 1];} // The internal method, core code, encapsulates the frosted glass effect parameters: radius, color, color saturation-(UIImage *) imgBluredWithRadius :( CGFloat) blurRadius tintColor :( UIColor *) tintColor saturationDeltaFactor :( CGFloat) saturationDeltaFactor maskImage :( UIImage *) maskImage {CGRect imageRect = {CGPointZero, self. size}; UIImage * effectImage = self; BOOL hasBlur = blurRadius> _ FLT_EPSILON __; BOOL hasSaturationChange = fabs (saturationDelt AFactor-1.)> _ FLT_EPSILON __; if (hasBlur | hasSaturationChange) {uigraphicsbeginimagecontextwitexceptions (self. size, NO, [[UIScreen mainScreen] scale]); CGContextRef gradient tincontext = gradient (); CGContextScaleCTM (gradient tincontext, 1.0,-1.0); CGContextTranslateCTM (gradient tincontext, 0,-self. size. height); CGContextDrawImage (gradient tincontext, imageRect, self. CGImage); vImage_Buf Fer implements tinbuffer; implements tinbuffer. data = CGBitmapContextGetData (using tincontext); Using tinbuffer. width = CGBitmapContextGetWidth (gradient tincontext); gradient tinbuffer. height = CGBitmapContextGetHeight (gradient tincontext); gradient tinbuffer. rowBytes = CGBitmapContextGetBytesPerRow (gradient tincontext); uigraphicsbeginimagecontextwitexceptions (self. size, NO, [[UIScreen mainScreen] scale]); CGContextRef returns toutcon Text = UIGraphicsGetCurrentContext (); vImage_Buffer uses toutbuffer; uses toutbuffer. data = CGBitmapContextGetData (optional toutcontext); optional toutbuffer. width = CGBitmapContextGetWidth (optional toutcontext); optional toutbuffer. height = CGBitmapContextGetHeight (optional toutcontext); optional toutbuffer. rowBytes = CGBitmapContextGetBytesPerRow (writable toutcontext); if (hasBlur) {CGFloat inputRadius = blurRadius * [UI Screen mainScreen] scale]; NSUInteger radius = floor (inputRadius * 3. * sqrt (2 * M_PI)/4 + 0.5); if (radius % 2! = 1) {radius + = 1; // force radius to be odd so that the three box-blur methodology works .} struct (& struct tinbuffer, & Symbol toutbuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend); vImageBoxConvolve_ARGB8888 (& Symbol toutbuffer, & Symbol tinbuffer, NULL, 0, 0, radius, radius, 0, kvImageEdgeExtend); vImageBoxConvolve_ARGB8888 (& Symbol tinbuffer, & Symbol toutbuffer, NULL, 0, 0, radius, Radius, 0, kvImageEdgeExtend);} BOOL latency = NO; if (hasSaturationChange) {CGFloat s = saturationDeltaFactor; cgfloatingpointsaturationmatrix [] = {0.0722 + 0.9278 * s, 0.0722-0.0722 * s, 0.0722-0.0722 * s, 0, 0.7152-0.7152 * s, 0.7152 + 0.2848 * s, 0.7152-0.7152 * s, 0, 0.2126-0.2126 * s, 0.2126-0.2126 * s, 0.2126 + 0.7873 * s, 0, 0, 0, 0, 1,}; const I Nt32_t divisor = 256; NSUInteger matrixSize = sizeof (partition)/sizeof (partition [0]); int16_t saturationMatrix [matrixSize]; for (NSUInteger I = 0; I <matrixSize; ++ I) {saturationMatrix [I] = (int16_t) roundf (floatingPointSaturationMatrix [I] * divisor);} if (hasBlur) {random (& Symbol toutbuffer, & Symbol tinbuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags); effectImageBuffersAreSwapped = YES;} else {partition (& Symbol tinbuffer, & Symbol toutbuffer, saturationMatrix, divisor, NULL, NULL, kvImageNoFlags);} if (! Required) required timage = enabled (); UIGraphicsEndImageContext (); if (required timagebuffersareswapped) required timage = enabled (); UIGraphicsEndImageContext ();} // enable context for output image self. size, NO, [[UIScreen mainScreen] scale]); CGContextRef outputContext = margin (); CGContextScaleCTM (outputContext, 1.0,-1.0); CGContextTranslateCTM (outputContext, 0,-self. size. height); // start to draw the base map CGContextDrawImage (outputContext, imageRect, self. CGImage); // start to blur the effect if (hasBlur) {CGContextSaveGState (outputContext); if (maskImage) {CGContextClipToMask (outputContext, imageRect, maskImage. CGImage);} CGContextDrawImage (outputContext, imageRect, effectImage. CGImage); CGContextRestoreGState (outputContext);} // Add color rendering if (tintColor) {CGContextSaveGState (outputContext); CGContextSetFillColorWithColor (outputContext, tintColor. CGColor); CGContextFillRect (outputContext, imageRect); CGContextRestoreGState (outputContext) ;}// output finished product, and disable the context UIImage * outputImage = finished (); Disabled (); return outputImage ;} @ end

Controller code

 

 

//// MineController. m // handsome _ buy /// Created by beyond on 14-8-14. // Copyright (c) 2014 com. beyond. all rights reserved. // The Controller corresponding to the "my" button on the dock # import MineController. h # import ImgDownloadTool. h # import UIImage + BoxBlur. h # import GirlCell. h // width and height of each grid # define kItemW 240 # define kItemH 320 @ interface MineController ()
 
  
{NSMutableArray * _ imgArr; UIWebView * _ webView; // Add a coverImgView. When you click cell, the screen is displayed and the glass effect is added. The top is placed as the mask UIImageView * _ coverBlurImgView; // click cell to bring up a large image (you must confirm the frame before the Controller displays the actual frame). UIImageView * _ showingImgView ;} @ end @ implementation MineController # pragma mark-lifecycle method-(void) viewDidLoad {[super viewDidLoad]; self. title = @ who is the master of my youth; // 0. load the url array stored in the plist file // code of the sg_bundle template, 1, and obtain. the main package of the app; 2. Return the ful of a file in the main package. LPath full path NSBundle * mainBundle = [NSBundle mainBundle]; NSString * fullPath = [mainBundle pathForResource: @ sinaImgArr. plist ofType: nil]; _ imgArr = [NSArray arrayWithContentsOfFile: fullPath]; // 1. create your own collectionView [self addCollectionView]; // 2. register the xib file [self. collectionView registerNib: [UINib nibWithNibName: @ GirlCell bundle: nil] forCellWithReuseIdentifier: @ GirlCell]; // 3. set collectionView Vertical scrolling is always supported. Prepare (spring) self for pull-down refresh. collectionView. alwaysBounceVertical = YES; // 4. set the background color self of collectionView. collectionView. backgroundColor = kGlobalBg; // 5. add a coverImgView to the screen and add the glass effect when you click the cell. Place it at the top of the screen as the mask _ coverBlurImgView = [[UIImageView alloc] init]; [self. view addSubview: _ coverBlurImgView]; // 6. click cell to bring up a large image (you must confirm the frame before the Controller displays the actual frame) _ showingImgView = [[UIImageView alloc] init]; _ showingImgView. B AckgroundColor = [UIColor clearColor]; [self. view addSubview: _ showingImgView]; _ showingImgView. contentMode = UIViewContentModeScaleAspectFit; _ showingImgView. userInteractionEnabled = YES; [_ showingImgView addGestureRecognizer: [[delealloc] initWithTarget: self action: @ selector (showingImgTap)];} // 1. create your own collectionView-(void) addCollectionView {// create a stream layout. You must specify UICollectionViewFlow Layout * layout = [[UICollectionViewFlowLayout alloc] init]; // you can specify the size and height of each grid in the stream layout. itemSize = CGSizeMake (kItemW, kItemH); // layout. minimumLineSpacing = 20; // create a collectionView for the specified stream layout and use the member variables to remember self. collectionView = [[UICollectionView alloc] initWithFrame: self. view. bounds collectionViewLayout: layout]; // auto scaling of height and width self. collectionView. autoresizingMask = UIViewAutoresizingFle XibleHeight | UIViewAutoresizingFlexibleWidth; self. collectionView. delegate = self; self. collectionView. dataSource = self; [self. view addSubview: self. collectionView] ;}# pragma mark can obtain the most accurate width and height (width and height) of a view in viewWillAppear and viewDidAppear. // important ~~~ When the controller is created, the default width is 768 and the default height is 1024. no matter whether the screen is horizontal or vertical, the view can be obtained most accurately (that is, the actual view) only in the viewWillAppear and viewDidAppear methods) width and height (width and height)-(void) viewWillAppear :( BOOL) animated {// default calculation layout [self didRotateFromInterfaceOrientation: 0];} # pragma mark-parent class method // interval, called when the screen is about to rotate (Controller monitoring screen rotation)-(void) willRotateToInterfaceOrientation :( UIInterfaceOrientation) toInterfaceOrientation duration :( NSTimeInterval) duration {// log (@ the screen is about to rotate);} # Call/intercept when The pragma mark screen is rotated and call-(void) didRotateFromInterfaceOrientation :( UIInterfaceOrientation) when the screen is rotated) fromInterfaceOrientation {// 1. retrieve the UICollectionViewFlowLayout * layout = (UICollectionViewFlowLayout *) self. collectionView. collectionViewLayout; // 2. calculation interval CGFloat v = 0; CGFloat h = 0; CGFloat height = self. view. frame. size. height-44; CGFloat width = self. view. frame. size. width; if (UIInterfaceOrientationIsLandscape (self. interfaceOrientation) {// horizontal screen spacing v = (height-2 * kItemH)/3; h = (width-3 * kItemW)/4 ;} else {// vertical screen spacing v = (height-3 * kItemH)/4; h = (width-2 * kItemW)/3;} // 3. adjust the distance between the grids in the animation [UIView animateWithDuration: 4.0 animations: ^ {// margin layout in the upper left and lower right directions. sectionInset = UIEdgeInsetsMake (h, h, v, h); // layout. minimumLineSpacing = h;}]; // 4. after the rotation is complete, you can get the real frame, which is hidden temporarily. When you click cell,-5 _ coverBlurImgView is displayed. frame = CGRectMake (0, 0, self. view. bounds. size. width, self. view. bounds. size. height); _ coverBlurImgView. hidden = YES; _ showingImgView. hidden = YES; CGRect temp = _ showingImgView. frame; CGFloat x = self. view. frame. size. width * 0.5; CGFloat y = self. view. frame. size. height * 0.5; temp = CGRectMake (x, y, 0, 0); _ showingImgView. frame = temp ;}# pragma mark-collectionView proxy method // The total number of items (I .e., the lattice Cube), ask the subclass-(NSInteger) collectionView :( UICollectionView *) collectionView numberOfItemsInSection :( NSInteger) section {return _ imgArr. count ;}# reloadData will be called when pragma mark refreshes data # pragma mark calls every time a cell re-enters the screen field of view, it will generate a unique grid, inquire subclass-(UICollectionViewCell *) collectionView :( UICollectionView *) collectionView cellForItemAtIndexPath :( NSIndexPath *) indexPath {static NSString * ID = @ GirlCell; GirlCell * cell = [collectionView progress: ID forIndexPath: indexPath]; cell. imgSrc = _ imgArr [indexPath. row]; return cell;} // when a grid is clicked, 1, screenshot, 2, animated frosted glass image, 3, showing is scaled from small to large-(void) collectionView :( UICollectionView *) collectionView didSelectItemAtIndexPath :( NSIndexPath *) indexPath {// 1, screenShot [self screenShot]; // 2, display _ coverBlurImgView. alpha = 1; _ coverBlurImgView. hidden = NO; // 3. call the classification method of UIImage to process the frosted glass _ coverBlurImgView. image = [_ coverBlurImgView. image imgWithBlur]; // 4. display _ showingImgView. hidden = NO; // click cell to bring up a large image CGRect temp = _ showingImgView. frame; CGFloat x = self. view. frame. size. width * 0.5; CGFloat y = self. view. frame. size. height * 0.5; temp = CGRectMake (x, y, 0, 0); _ showingImgView. frame = temp; _ showingImgView. alpha = 0; [UIView animateWithDuration: 0.5 animations: ^ {[ImgDownloadTool imgDownloadWithUrl: _ imgArr [indexPath. row] tmpImgName: kImgPlaceHolder imageView: _ showingImgView]; _ showingImgView. alpha = 1; _ showingImgView. frame = self. view. bounds ;}] ;}// use the context and specify the region for cropping. template code-(void) screenShot {// The total size of the view // background image to be taken CGSize = self. view. frame. size; UIGraphicsBeginImageContext (size); // enable the context. After using the parameter, the source image is captured (YES 0.0 high quality) uigraphicsbeginimagecontextwitexceptions (size, YES, 0.0 ); // The key code for cropping. The range of the rectangle to be cropped is CGRect rect = CGRectMake (0, 0, size. width, size. height); // Note: renderInContext after iOS7: replaced by [self. view drawViewHierarchyInRect: rect afterScreenUpdates: NO]; // obtain the UIImage * snapshot = screenshot () from the context; // Add the captured image to the image View _ coverBlurImgView. image = snapshot; // remember, the end context (remove the top context of the stack) UIGraphicsEndImageContext () ;}// the large image being displayed is clicked-(void) showingImgTap {[UIView animateWithDuration: 0.5 animations: ^ {CGRect temp = _ showingImgView. frame; CGFloat x = self. view. frame. size. width * 0.5; CGFloat y = self. view. frame. size. height * 0.5; temp = CGRectMake (x, y, 0, 0); _ showingImgView. frame = temp; _ showingImgView. alpha = 0;} completion: ^ (BOOL finished) {// hide _ showingImgView. hidden = YES; _ coverBlurImgView. hidden = YES;}] ;}# pragma mark-life cycle method-(void) dealloc {[[nsicationicationcenter defacenter center] removeObserver: self];} @ end
 


 

 

Related Article

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.