Shadows and gradients for IOS 2D drawing (quartz2d) (shadow,gradient)

Source: Internet
Author: User
Tags abstract definition

Original Blog Address: http://blog.csdn.net/hello_hwc/article/details/49507881

Shadow

The purpose of Shadow (shadow) is to make the UI more stereoscopic,

There are three main factors affecting shadow

X off-Set  determines the shadow along the x offset y off-set  determines the offset of the shadow along y blur value determines whether the edge area of the shadow is blurred

A diagram of the different blur effects

Attention:

Shadow is also associated with drawing states, meaning that if you just draw a subpath shadow, be aware that save and restore

Related functions

Cgcontextsetshadowcgcontextsetshadowwithcolor // The only difference is that the shadow color is set

Parameters

Context Drawing Artboards

Offset shadow offsets, referencing context's coordinate system

Blur non-negative numbers to determine how blurry the shadows are

Sample code

- (void) DrawRect: (cgrect) Rect {cgcontextref context=Uigraphicsgetcurrentcontext (); //fill the border of course you can use layer settingsCgcontextsetstrokecolorwithcolor (context, [Uicolor Darkgraycolor].    Cgcolor); Cgcontextsetfillcolorwithcolor (context, [Uicolor Whitecolor].    Cgcolor);    Cgcontextfillrect (context, rect);        Cgcontextstrokerect (context, rect); Cgcontextaddarc (Context, -, -, -,0, M_2_PI,0);    Cgcontextsetlinecap (context, kcglinecapround); Cgcontextsetlinewidth (Context,3.0); Cgcontextsetshadow (Context, Cgsizemake (4.0,4.0),1.0); //Cgcontextsetshadowwithcolor (Context, Cgsizemake (4.0, 4.0), 1.0, [Uicolor Bluecolor]. Cgcolor);Cgcontextstrokepath (context);}

Effect

Gradient Fade Color

The gradient is nothing more than a gradual transformation from one color to another, Quartz 2D provides two models of gradients.

Quartz provides two opaque data Odgago create gradients: Cgshadingref and cggradientref. We can use either of these to create an axial (axial) or radial (radial) gradient. A gradient is a fill from one color to another.

An axial gradient (also known as a linear gradient) is a gradient of the axes connected along the two endpoints. All points in a line perpendicular to the axis have the same color value.

A radial gradient is also an axis gradient that is connected along the two endpoints, although the path is usually defined by a two circle.

1> axial gradient linear gradient (axial gradient), when used to set the color of two vertices (you can also set the middle transition color)

For example:

Axial gradient from orange to yellow gradient in this example, the gradient axis tilts at a 45 degree angle relative to the far point.

Quartz also allows us to set a series of color values and position values to create more complex axial gradients along the axis. As shown, the color of the starting point is set to red (you can see the quartz coordinate system 0 points by default is the bottom left), the color of the end point is violet. At the same time, there are 5 positions on the axis, their colors are set to orange green blue and indigo respectively. We can think of it as a continuous linear gradient of six segments along the same axis. Another axis angle is defined by the two endpoints we set.

2> Radial Gradient (radial gradient)

This pattern of gradients allows a gradient of one circle to another circle

As shown, he graduated from a small bright red circle to a size black circle,

We can place a circle in a radial gradient to create a variety of shapes. If one circle is part of another or is completely outside the other, Quartz creates a cone and a cylinder. A common use of radial gradients is to create a sphere shadow

A single point (circle with a radius of 0) is within a large circle.

Comparison of cgshading and Cggradient objects

We have two object types for creating gradients, and you might want to know which one is better, and you'll know what you see below.

Cgshadingref This opaque data type gives us more control over how to calculate the color of each endpoint, before we create the Cgshading object, we have to create a Cgfunction object (CGFUNCTIONREF), This object defines a function for calculating the gradient color. Write a custom function that lets us create a smooth gradient.

When we create a Cgshading object, we specify whether it is axial or radial, and we need to provide a color space in addition to the calculation function. The start point end point or radius, depending on whether you are drawing an axial or radial gradient. When drawing, we simply pass the Cgshading object and draw the context to the cgcontextdrawshading function, quartz call the gradient calculation function for each point on the gradient.

A Cggradient object is a subset of the Cgshading object, which is easier to use and cggradientref an opaque type of depression because quartz calculates the color value at each point in the gradient. We do not need to provide a gradient calculation function. When creating a Gradient object, we provide an array of positions and colors. Quartz uses the corresponding color values to calculate the gradient for each gradient. We can use a single imposing and ending point to set a Gradient object. or provide a set of power outages to create a multi-color gradient effect. The ability to use a Cgshading object can provide more than two locations.

When we create a Cggradient object, we need to set a color space, a position, and a color value for each position. When using a gradient object to draw the context, we specify whether the quartz is to draw an axial or radial gradient. When drawing, we specify the starting end point or radius, depending on whether we are drawing an axial or radial gradient. The geometry of cgshading is defined at creation time, not when it is drawn.

Extend the color outside the gradient endpoint

When we create a gradient, we can choose to fill the space outside the gradient endpoint with a solid color. Quartz uses the color on the gradient boundary as the fill color. We can expand the color of the start, end, or both ends of the gradient. We can extend an axial or radial gradient created using Cgshading objects or Cggradient objects.

The figure illustrates an axial gradient that expands the areas on both sides of the start and end points. The segments in the picture Show the axis of the gradient. We can see that the fill color corresponds to the color of the start and end points.

Use Quartz 2D to draw very beautiful graphics with these two gradient nesting

Two kinds of drawing models for gradients

Cgshading-Using this data type requires you to define your own cffunction to calculate the gradient of each point, more complex, but flexible to draw.

cggradient-Use this data type only need to make two vertex color, as well as the drawing mode, the rest of the quartz will be drawn, but the mathematical model of the gradient is not flexible.

Use the Cggradient object:

An Cggradient object is an abstract definition of a gradient his simple texture has a color value and position, but no geometry is specified, and we can use this object in both axial and radial geometries as an axial definition, Cggradient objects may be easier to reuse than cgshading objects. No geometry is said to be stored in the Cggradient object. This allows us to use the same color scheme to draw different geometries without the need to create multiple Cggadient objects for multiple graphics.

Because Quartz calculates gradients for us, it is more straightforward to use a Cggradient object to create and draw a gradient, just the following steps:

1> creates a Cggradient object that provides a color space, an array of two or more color components, an array of two or more locations, and the number of elements in the two array.

2> is drawn using cgcontextdrawlineargradient or cgcontentdrawradialgradient.

3> Releasing Cggradient objects

A position is a value range between 0.0 and 1.0, and he specifies the value of the normalized distance value 0.0 along the axis of the gradient to specify the starting point of the axis, and the value of 1.0 specifies the cgfloat of the axis. Other values specify a scale for a distance. At a minimum, the quartz uses two position values. If we pass a null value as a positional array parameter, then quartz uses 0 as the first position and 1 as the second position.

The number of color components per color depends on the color space. For off-screen drawing, we use an RGB color space. Because quartz is drawn using alpha, each off-screen color has four components-red, green, blue, and Alpha. So, for off-screen drawing, the number of elements in the array of color components we provide must be 4 times times the number of positions. The Rgba color component of quartz can be changed from 0.0 to 1.0.

Code

- (void) DrawRect: (cgrect) Rect {cgcontextref context=Uigraphicsgetcurrentcontext (); //drawing with CggradientCgcolorspaceref Devicergb =Cgcolorspacecreatedevicergb (); size_t num_of_locations=2;
Note that each location corresponds to a color cgfloat locations[2] = {0.0,1.0}; CGFloat components[8] = {1.0,0.0,0.0,1.0,//Red 0.0,1.0,0.0,1.0};//GreenCggradientref gradient =cggradientcreatewithcolorcomponents (DEVICERGB, components, locations, num_of_locations); Cgpoint StartPoint= Cgpointmake (0,0); Cgpoint EndPoint=Cgpointmake (Rect.size.width, rect.size.height); Cgcontextdrawlineargradient (context, gradient, StartPoint, EndPoint,0); Cgcolorspacerelease (DEVICERGB); Cggradientrelease (gradient);}

Effect

Radial gradient

Cgcontextref context =Uigraphicsgetcurrentcontext (); //Color SpaceCgcolorspaceref Devicergb =Cgcolorspacecreatedevicergb (); //position arrays and color arrays contain the number of elementssize_t num_of_locations =2; CGFloat locations[2] = {0.0,1.0}; CGFloat components[8] = {0.0,0.0,1.0,1.0,//White        0.0,1.0,0.0,1.0};//BlackCggradientref gradient =cggradientcreatewithcolorcomponents (DEVICERGB, components, locations, num_of_locations); Cgpoint Startcenter= Cgpointmake ( -, -); Cgpoint Endcenter= Cgpointmake ( the, the); CGFloat Startradius=0.0; CGFloat Endradius=50.0; Cgcontextdrawradialgradient (context, gradient, Startcenter, Startradius, Endcenter, Endradius,0);    Cgcolorspacerelease (DEVICERGB); Cggradientrelease (gradient);

Using the Cgshading object

We set a gradient by calling the function cgshadingcreateaxial or cgshadingcreateradial to create a Cgshading object that requires the following parameters to be called.

1.CGColorSpace object: Color space

2. Starting and ending points. For an axial gradient, the coordinates of the starting and ending points of the axis, and for the radial gradient, the center coordinate of the start circle and the end point

3. The radius of revelation and the ending radius of the circle used to define the gradient area

4. A Cgfunction object, which can be obtained through the cgfunctioncreate function. This callback routine must return a color value drawn to a specific point.

5. A Boolean value that specifies whether a solid color is used to draw the extended area of the start and end points

The Cgfunction object that we provide to cgshading to create the function contains a callback struct, and all the information quartz needs to implement this callback. Perhaps the trickiest part of setting up a Cgshasing object is creating a Cgfunction object. When we call the Cgfunctioncreate function, we provide the following parameters:

cgfunctionref _nullable cgfunctioncreate (   void * _nullable info,   size_t Domaindimension,   const cgfloat * _nullable domain,   size_t rangedimension,     Const CGFloat * _nullable range,   const cgfunctioncallbacks * _nullable Callbacks );

You see this is a headache? Of course, cggradient is enough to satisfy most of the time, but be patient and take a look when you are free. Let's look at the parameters first

Info is used to pass data to callback (a pointer to the data needed by the callback), noting that his life cycle may not be just the life cycle of the method

The number of domaindimesion inputs, in Quart, is 1. (number of callback input values, Quartz requires callback to carry one input value)

Domain A set of data determines the valid interval of input, in quartz is 0 to 1,0 to start, and 1 for the end (an array of floating-point numbers. Quartz only provides an element in the array to the callback function. The range of a transfer value is 0 (the color of the start point of the gradient) to 1 (the color of the end point of the gradient). )

Rangdimension Output: (Number of output values provided by the callback, for each input value, our callback must provide a value for each color component, and an alpha value to specify the transparency, the color component value is interpreted by the color space provided by quartz, and provide to cgshading create function. For example, if we use the RGB color space, we provide 4 as the number of output values (R,G,B,A))

Rang valid interval for output (an array of floating-point numbers that specifies the value and alpha value of each color component)

Callbacks the actual method used to calculate (a callback data structure that contains the version of the struct (set to 0), a callback that generates a color component value, and an optional data that is used to release the info parameter in the callback. The format is as follows void Mycalculateshadingvalues (void *info, const cgfloat *in, CGFloat *out)

After creating the Cgshading object, we can set additional cut operations if needed. Then call the Cgcontextdrawshading function to use the gradient to draw the clipping region of the context. When this function is called, quartz calls the callback function to get the color value from the starting point to the end of the range.

When the Cgshading object is no longer needed, we call cgshadingrelease to release it.

First set the Cgfunction object to calculate the color value

We can calculate the color value in the way we want, our color calculation function contains the following three parameters:

1.void *info This value can be null or a pointer to the data passed to the Cgshading creation function

2.const cgfloat *in Quartz Pass in array to callback. The values in the array must be within the range of the input values defined for the Cgfunction object

3. Our callback function passes the out array to quartz. It contains elements for each color component in the color space and an alpha value. The output value should be within the range of the output values defined in the Cgfunction object

Static voidMycalculateshadingvalues (void*info,ConstCGFloat *inch, CGFloat* out) {CGFloat v;    size_t k, components; Static ConstCGFloat c[] = {1,0,0.5,0 }; components=(size_t) info; V= *inch;  for(k =0; K < Components-1; k++)        * out+ + = c[k] *v; * out++ =1;}

Here are the three parameters, the function is very simple out of the value (R,G,B,A) respectively (in*1,in*0.in*0.5,1)

Create a Cgfuction

StaticCgfunctionref mygetfunction (Cgcolorspaceref colorspace)//1 {size_t numcomponents;Static ConstCGFloat Input_value_range [2] = {0,1 };Static ConstCGFloat Output_value_ranges [8] = {0,1,0,1,0,1,0,1};Static ConstCgfunctioncallbacks callbacks = {0,//2&mycalculateshadingvalues, NULL};numcomponents=1+ cgcolorspacegetnumberofcomponents (colorspace);//3 returnCgfunctioncreate ((void*) Numcomponents,1, Input_value_range, Numcomponents, Output_value_ranges, &callbacks); }

where each line is

Take colorspace as a parameter
Defining the callback function
Calculates the number of color builds in the Color field, such as RGB, which is three, and then adds one to represent the alpha channel

Draw axial Gradient with cgshading

cgpoint StartPoint, EndPoint; Cgfunctionref Myfunctionobject; Cgshadingref Myshading;startpoint= Cgpointmake (0,0.5); EndPoint= Cgpointmake (1,0.5); ColorSpace=Cgcolorspacecreatedevicergb (); Myfunctionobject=mygetfunction (colorspace); Myshading=cgshadingcreateaxial (ColorSpace, StartPoint, EndPoint, Myfunctionobjec T,false,false) cgcontextdrawshading (Mycontext, myshading); Cgshadingrelease (myshading); Cgcolorspacerelease (ColorSpace); Cgfunctionrelease (myfunctionobject);

Draw radial Gradient with cgshading

Callback

Static voidMycalculateshadingvalues (void*info,ConstCGFloat *inch, CGFloat* out) {size_t k, components; Doublefrequency[4] = { -, -, the,0 }; components=(size_t) info;  for(k =0; K < Components-1; k++)        * out++ = (1+ Sin (*inch* Frequency[k])/2; * out++ =1;//Alpha}
cgpoint StartPoint, EndPoint;      CGFloat Startradius, Endradius; StartPoint= Cgpointmake (0.25,0.3); Startradius= .1; EndPoint= Cgpointmake (.7,0.7); Endradius= . -; ColorSpace=Cgcolorspacecreatedevicergb (); Myshadingfunction=mygetfunction (colorspace);                      Cgshadingcreateradial (ColorSpace, StartPoint, Startradius, EndPoint, Endradius, Myshadingfunction,false,                      false) cgcontextdrawshading (mycontext, shading); Cgshadingrelease (myshading); Cgcolorspacerelease (ColorSpace); Cgfunctionrelease (myfunctionobject);

See here Http://www.tuicool.com/articles/biieum for specific effects

My level still a little to understand AH

Shadows and gradients for IOS 2D drawing (quartz2d) (shadow,gradient)

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.