Ios_ Custom frosted Glass effect

Source: Internet
Author: User

Eventually:







Key code:




UIImage Classification code

  uiimage+blurglass.h//  Handsome _ buy////  Created by Beyond on 14-8-30.//  Copyright (c) 2014 Com.beyond. All rights reserved.//  Glass effect UIImage classification #import <UIKit/UIKit.h> @interface UIImage (blurglass)/* 1. White, Parameters: transparency 0~ 1,  0 is white,   1 is dark gray radius: Default 30, Recommended value 3   radius value is more blurred, the smaller the value the more clearly the color saturation (concentration) Factor:  0 is black and white gray, 9 is thick color, 1 is the  default 1.8 "Color" of the primary color, English is called saturation, that is, saturation. The color-free black and white Gray is set to 0, the most vivid 9s, so roughly divided into 10 stages, so that the values and the human senses intuition consistent. */-(UIImage *) Imgwithlightalpha: (cgfloat) Alpha radius: (cgfloat) Radius colorsaturationfactor: (cgfloat) colorsaturationfactor;//2. Packaged for external invocation-(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 <Accelerate/Accelerate.h> @implementation UIImage (  Blurglass)/* 1. White, Parameters: Transparency 0~1, 0 is white, 1 is dark gray radius: Default 30, recommended 3 radius value is more blurred, the smaller the value the more clearly the color saturation (concentration) Factor: 0 is black and white gray, 9 is a thick color, 1 is the primary color The default 1.8 "color", English is called saturation, that is, saturation. The color-free black and white Gray is set to 0, the most vivid 9s, so roughly divided into 10 stages, so that the values and the human senses intuition consistent. */-(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 ];} Internal method, core code, encapsulated 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 (saturationDeltaFactor-1.) > __flt_epsilon__; if (Hasblur | | hassaturationchange) {uigraphicsbeginimagecontextwithoptions (self.size, NO, [[UIScreen MainScreen]        Scale]);        Cgcontextref Effectincontext = Uigraphicsgetcurrentcontext ();        CGCONTEXTSCALECTM (Effectincontext, 1.0,-1.0);        CGCONTEXTTRANSLATECTM (effectincontext, 0,-self.size.height); Cgcontextdrawimage (Effectincontext, imagerect, self.                Cgimage);        Vimage_buffer Effectinbuffer;        Effectinbuffer.data = Cgbitmapcontextgetdata (Effectincontext);        Effectinbuffer.width = Cgbitmapcontextgetwidth (Effectincontext);        Effectinbuffer.height = Cgbitmapcontextgetheight (Effectincontext); Effectinbuffer.rowbytes = CgbitmaPcontextgetbytesperrow (Effectincontext);        Uigraphicsbeginimagecontextwithoptions (Self.size, NO, [[UIScreen mainscreen] scale]);        Cgcontextref Effectoutcontext = Uigraphicsgetcurrentcontext ();        Vimage_buffer Effectoutbuffer;        Effectoutbuffer.data = Cgbitmapcontextgetdata (Effectoutcontext);        Effectoutbuffer.width = Cgbitmapcontextgetwidth (Effectoutcontext);        Effectoutbuffer.height = Cgbitmapcontextgetheight (Effectoutcontext);                Effectoutbuffer.rowbytes = Cgbitmapcontextgetbytesperrow (Effectoutcontext);            if (Hasblur) {cgfloat Inputradius = Blurradius * [[UIScreen mainscreen] scale];            Nsuinteger radius = Floor (Inputradius * 3. * SQRT (2 * m_pi)/4 + 0.5);             if (radius% = 2 = 1) {radius + = 1;//force radius to is odd so, the three Box-blur methodology works. } vimageboxconvolve_argb8888 (&effectinbuffer, &effectoutbuffer, NULL, 0, 0, radius, radius, 0, kvimageedgeextend); vimageboxconvolve_argb8888 (&effectoutbuffer, &effectinbuffer, NULL, 0, 0, radius, radius, 0, Kvimageedgeextend            ); vimageboxconvolve_argb8888 (&effectinbuffer, &effectoutbuffer, NULL, 0, 0, radius, radius, 0, Kvimageedgeextend        );        } BOOL effectimagebuffersareswapped = NO;            if (Hassaturationchange) {cgfloat s = saturationdeltafactor; CGFloat floatingpointsaturationmatrix[] = {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 int32_t DIVISOR = 256;            Nsuinteger matrixsize = sizeof (Floatingpointsaturationmatrix)/sizeof (floatingpointsaturationmatrix[0]); int16_t SaturaTionmatrix[matrixsize]; for (Nsuinteger i = 0; i < matrixsize; ++i) {Saturationmatrix[i] = (int16_t) roundf (Floatingpointsaturat            Ionmatrix[i] * divisor); } if (Hasblur) {vimagematrixmultiply_argb8888 (&effectoutbuffer, &effectinbuffer, Satura                Tionmatrix, divisor, NULL, NULL, KVIMAGENOFLAGS);            effectimagebuffersareswapped = YES; } else {vimagematrixmultiply_argb8888 (&effectinbuffer, &effectoutbuffer, Saturationmatr            IX, divisor, NULL, NULL, KVIMAGENOFLAGS);         }} if (!effectimagebuffersareswapped) effectimage = Uigraphicsgetimagefromcurrentimagecontext ();                Uigraphicsendimagecontext ();        if (effectimagebuffersareswapped) effectimage = Uigraphicsgetimagefromcurrentimagecontext ();    Uigraphicsendimagecontext (); }//Open context for output image uigraphicsbeginimagecontextwithoptions (Self.size, NO, [[UIScreen Mainscreen] scale]);    Cgcontextref Outputcontext = Uigraphicsgetcurrentcontext ();    CGCONTEXTSCALECTM (Outputcontext, 1.0,-1.0);        CGCONTEXTTRANSLATECTM (outputcontext, 0,-self.size.height); Start drawing the Basemap cgcontextdrawimage (Outputcontext, imagerect, self.        Cgimage);        Start drawing blur 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);    }//outputs the finished product and closes the context UIImage *outputimage = Uigraphicsgetimagefromcurrentimagecontext ();        Uigraphicsendimagecontext (); 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 "my" button on the dock above the controller #import "MineController.h" #import "ImgDownloadTool.h" #import < accelerate/accelerate.h> #import "Uiimage+boxblur.h" #import "GirlCell.h"//width of each lattice and high # define KITEMW 240#define KITEMH 320@interface Minecontroller () <uicollectionviewdatasource,uicollectionviewdelegate>{NSMutableArray *    _imgarr;        UIWebView *_webview;    Add a Coverimgview, for clicking on the cell, the screen and add a glass effect, placed at the top as a mask uiimageview *_coverblurimgview; Click cell, pop up a large image (you must confirm the frame, the real frame before the controller is displayed) Uiimageview *_showingimgview;}    @end @implementation Minecontroller#pragma Mark-life cycle Method-(void) viewdidload{[Super Viewdidload];    Self.title = @ "Who decides my youth"; 0. Load the plist file to save the URL array//sg_bundle template code, 1, get the. App main package; 2, return the FullPath full path of a file in the main package nsbundle *mainbundle = [NSBundle main    Bundle]; NSString *fullpath = [Mainbundle pathforresource:@ "Sinaimgarr.plist" Oftype:nil];                    _imgarr = [Nsarray Arraywithcontentsoffile:fullpath];        1. Create your own CollectionView [self addcollectionview]; 2. xib file to be used for registering cell lattice [Self.collectionview registernib:[uinib nibwithnibname:@ "Girlcell" Bundle:nil]        forcellwithreuseidentifier:@ "Girlcell"];        3. Set CollectionView to always support vertical scrolling, ready for pull-down refresh (Spring) self.collectionView.alwaysBounceVertical = YES;        4. Set the background color of the collectionview Self.collectionView.backgroundColor = KGLOBALBG;    5. Add a Coverimgview, for click on the cell, the screen and add a frosted glass effect, placed at the top as a mask _coverblurimgview = [[Uiimageview alloc]init];            [Self.view Addsubview:_coverblurimgview];    6. Click on the cell to bring up a large image (you must confirm the frame before the controller is displayed, the real frame) _showingimgview = [[Uiimageview alloc]init];    _showingimgview.backgroundcolor = [Uicolor Clearcolor];    [Self.view Addsubview:_showingimgview];    _showingimgview.contentmode = Uiviewcontentmodescaleaspectfit;    _showingimgview.userinteractionenabled = YES; [_showingimgview Addgesturerecognizer:[[uitApgesturerecognizer Alloc] initwithtarget:self action: @selector (SHOWINGIMGTAP)];} 1. Create your own collectionview-(void) addcollectionview{//Create a flow layout, you must specify uicollectionviewflowlayout *layout = [[Uicollecti    Onviewflowlayout alloc] init];    Set the flow layout inside each grid width and height, that is, the size of each grid layout.itemsize = Cgsizemake (KITEMW, KITEMH);    The spacing between each line layout.minimumlinespacing = 20; Specify the flow layout to create a collectionview, and use member variables to remember self.collectionview = [[Uicollectionview alloc] InitWithFrame:self.view.bounds    Collectionviewlayout:layout]; Height and width auto-scaling self.collectionView.autoresizingMask = Uiviewautoresizingflexibleheight |    Uiviewautoresizingflexiblewidth;    Self.collectionView.delegate = self;    Self.collectionView.dataSource = self; [Self.view AddSubview:self.collectionView];} #pragma mark can get the most accurate width and height of the view in Viewwillappear and Viewdidappear//Important ~ ~ ~ because when the controller is created, the width default is 768, the high default is 1024, regardless of the screen//   Only in the Viewwillappear and Viewdidappear methods can you get the view's most accurate (that is, the actual) width and height (width and height)-(void) Viewwillappear: (BOOL) animated{ Default calculation layout [self didrotatefrominterfaceorientation:0];} #pragma mark-parent method//intercept, call when screen is about to rotate (Controller monitor screen rotation)-(void) Willrotatetointerfaceorientation: (uiinterfaceorientation) Tointerfaceorientation Duration: (nstimeinterval) duration{//log (@ "screen is about to rotate");} #pragma mark screen is rotated at the end of the call//intercept, when screen rotation is complete call-(void) Didrotatefrominterfaceorientation: (uiinterfaceorientation)    frominterfaceorientation{//1. Remove the uicollectionviewflowlayout that was passed in when the Collectionviewcontroller was created            Uicollectionviewflowlayout *layout = (uicollectionviewflowlayout *) self.collectionView.collectionViewLayout;    2. Calculate the spacing 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)) {//cross-screen spacing v = (height-2 * KItem        H)/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 squares of the animation [UIView animatewithduration:4.0 animations:^{//Margin layout.section in the upper left and right four directions        Inset = Uiedgeinsetsmake (H, H, V, h);    The spacing between each line layout.minimumlinespacing = h;        }]; 4. After the rotation is complete, you can get the real frame, temporarily hidden, when clicking on the cell's directs show-5 _coverblurimgview.frame = CGRectMake (0, 0, Self.view.bounds.size.wi    DTH, 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//Total number of item (that is, lattice cube), ask sub-class-(Nsinteger) CollectionView: (Uicollectionview *) CollectionView numberofitemsinsection: (nsinteger) section{return _imgarr.count;} #pragma mark is called when the data is refreshed (reloaddata) #pragma mark calls//generates each unique lattice whenever a cell re-enters the screen field of view, asking the subclass-(Uicollectionviewcell * ) CollectionvieW: (Uicollectionview *) CollectionView Cellforitematindexpath: (Nsindexpath *) indexpath{static NSString *ID = @ "GirlCell    ";        Girlcell *cell = [CollectionView dequeuereusablecellwithreuseidentifier:id Forindexpath:indexpath];        CELL.IMGSRC = _imgarr[indexpath.row]; return cell;} When clicked on a lattice, 1, screenshot, 2, animated frosted glass picture, 3,showing 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 UIImage classification method, the glass processing _coverblurimgview.image = [_coverblurimgview.image Imgwithblur];            4. Show _showingimgview _showingimgview.hidden = NO;    Click cell, pop 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:kImgPlaceHo        Lder Imageview:_showingimgview];        _showingimgview.alpha = 1;    _showingimgview.frame = Self.view.bounds;    }];    }//uses the context, and uses the specified area to crop, template code-(void) screenshot{//The total size of the view//background picture to be cgsize by the sizes = Self.view.frame.size;    Uigraphicsbeginimagecontext (size);    Open context, after using the parameter, the original (yes 0.0 high quality) uigraphicsbeginimagecontextwithoptions (size, yes, 0.0) is truncated;    The clipping of the key code, the rectangular range to be clipped cgrect rect = CGRectMake (0, 0, size.width, size.height);  Note: IOS7 after Renderincontext: by drawviewhierarchyinrect:afterscreenupdates: alternative [Self.view drawviewhierarchyinrect:rect    Afterscreenupdates:no];    From the context, remove UIImage UIImage *snapshot = Uigraphicsgetimagefromcurrentimagecontext ();        Add the captured picture to the picture view inside _coverblurimgview.image = snapshot;    Remember, end context (remove stack top) uigraphicsendimagecontext ();                The large image}//is being displayed is ordered-(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) {//hidden up _showingimgview.hidden = YES;    _coverblurimgview.hidden = YES; }];} #pragma mark-life cycle Method-(void) dealloc{[[Nsnotificationcenter Defaultcenter] removeobserver:self];} @end









Ios_ Custom frosted Glass effect

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.