iOS開發(fā)-OpenGL ES畫圖應(yīng)用

這是一篇OpenGL ES的實戰(zhàn),緊接 入門教程3
學(xué)了OpenGL ES一段時間,用這個應(yīng)用來練練手。

OpenGL ES系列教程在這里
OpenGL ES系列教程的代碼地址 - 你的star和fork是我的源動力,你的意見能讓我走得更遠(yuǎn)。

效果展示

實戰(zhàn).gif

demo來自蘋果官方,可以學(xué)習(xí)蘋果的工程師如何應(yīng)用OpenGL ES。
這次的內(nèi)容包括,shaderCoreGraphics手勢識別運動軌跡模糊點效果

shader

自定義enum,方便OC與shader之間的賦值,配合下面的自動assign功能,非常便捷。

enum {
    PROGRAM_POINT,
    NUM_PROGRAMS
};

enum {
    UNIFORM_MVP,
    UNIFORM_POINT_SIZE,
    UNIFORM_VERTEX_COLOR,
    UNIFORM_TEXTURE,
    NUM_UNIFORMS
};

enum {
    ATTRIB_VERTEX,
    NUM_ATTRIBS
};

typedef struct {
 char *vert, *frag;
 GLint uniform[NUM_UNIFORMS];
 GLuint id;
} programInfo_t;

programInfo_t program[NUM_PROGRAMS] = {
    { "point.vsh",   "point.fsh" },     // PROGRAM_POINT
};

創(chuàng)建program的過程,用glBindAttribLocation()glueGetUniformLocation ()來綁定attribute和uniform變量。

/* Convenience wrapper that compiles, links, enumerates uniforms and attribs */
GLint glueCreateProgram(const GLchar *vertSource, const GLchar *fragSource,
                       GLsizei attribNameCt, const GLchar **attribNames, 
                       const GLint *attribLocations,
                       GLsizei uniformNameCt, const GLchar **uniformNames, 
                       GLint *uniformLocations,
                       GLuint *program)
{
 GLuint vertShader = 0, fragShader = 0, prog = 0, status = 1, i;
 
 prog = glCreateProgram();

 status *= glueCompileShader(GL_VERTEX_SHADER, 1, &vertSource, &vertShader);
 status *= glueCompileShader(GL_FRAGMENT_SHADER, 1, &fragSource, &fragShader);
 glAttachShader(prog, vertShader);
 glAttachShader(prog, fragShader);
 
 for (i = 0; i < attribNameCt; i++)
 {
  if(strlen(attribNames[i]))
   glBindAttribLocation(prog, attribLocations[i], attribNames[i]);
 }
 
 status *= glueLinkProgram(prog);
 status *= glueValidateProgram(prog);

 if (status)
 { 
        for(i = 0; i < uniformNameCt; i++)
  {
            if(strlen(uniformNames[i]))
       uniformLocations[i] = glueGetUniformLocation(prog, uniformNames[i]);
  }
  *program = prog;
 }
 if (vertShader)
  glDeleteShader(vertShader);
 if (fragShader)
  glDeleteShader(fragShader);
 glError();
  
 return status;
}

shader的編譯之前困擾過我很久,這個demo介紹了一種方法可以獲取編譯錯誤信息,非常的nice。

#define glError() { \
 GLenum err = glGetError(); \
 if (err != GL_NO_ERROR) { \
  printf("glError: %04x caught at %s:%u\n", err, __FILE__, __LINE__); \
 } \
}

CoreGraphics

自定義textureInfo_t結(jié)構(gòu)體,在textureFromName()用CoreGraphics把url對應(yīng)的image data緩存到OpenGLES,并通過textureInfo_t返回信息。

// Texture
typedef struct {
    GLuint id;
    GLsizei width, height;
} textureInfo_t;

// Create a texture from an image
- (textureInfo_t)textureFromName:(NSString *)name
{
    CGImageRef  brushImage;
 CGContextRef brushContext;
 GLubyte   *brushData;
 size_t   width, height;
    GLuint          texId;
    textureInfo_t   texture;
    
    // First create a UIImage object from the data in a image file, and then extract the Core Graphics image
    brushImage = [UIImage imageNamed:name].CGImage;
    
    // Get the width and height of the image
    width = CGImageGetWidth(brushImage);
    height = CGImageGetHeight(brushImage);
    
    // Make sure the image exists
    if(brushImage) {
        // Allocate  memory needed for the bitmap context
        brushData = (GLubyte *) calloc(width * height * 4, sizeof(GLubyte));
        // Use  the bitmatp creation function provided by the Core Graphics framework.
        brushContext = CGBitmapContextCreate(brushData, width, height, 8, width * 4, CGImageGetColorSpace(brushImage), kCGImageAlphaPremultipliedLast);
        // After you create the context, you can draw the  image to the context.
        CGContextDrawImage(brushContext, CGRectMake(0.0, 0.0, (CGFloat)width, (CGFloat)height), brushImage);
        // You don't need the context at this point, so you need to release it to avoid memory leaks.
        CGContextRelease(brushContext);
        // Use OpenGL ES to generate a name for the texture.
        glGenTextures(1, &texId);
        // Bind the texture name.
        glBindTexture(GL_TEXTURE_2D, texId);
        // Set the texture parameters to use a minifying filter and a linear filer (weighted average)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
        // Specify a 2D texture image, providing the a pointer to the image data in memory
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, (int)width, (int)height, 0, GL_RGBA, GL_UNSIGNED_BYTE, brushData);
        // Release  the image data; it's no longer needed
        free(brushData);
        
        texture.id = texId;
        texture.width = (int)width;
        texture.height = (int)height;
    }
    
    return texture;
}

手勢識別

這里的手勢只有點擊和滑動,通過記錄touchesBegan,獲取第一個點的位置,之后滑動的過程中touchesMoved獲取到這次的位置和上次的位置,可以畫出一道手指滑動的軌跡,通過renderLineFromPoint()繪制。

// Handles the start of a touch
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{   
 CGRect    bounds = [self bounds];
 UITouch*   touch = [[event touchesForView:self] anyObject];
 firstTouch = YES;
 // Convert touch point from UIView referential to OpenGL one (upside-down flip)
 location = [touch locationInView:self];
 location.y = bounds.size.height - location.y;
}

// Handles the continuation of a touch.
- (void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{   
 CGRect    bounds = [self bounds];
 UITouch*   touch = [[event touchesForView:self] anyObject];
  
 // Convert touch point from UIView referential to OpenGL one (upside-down flip)
 if (firstTouch) {
  firstTouch = NO;
  previousLocation = [touch previousLocationInView:self];
  previousLocation.y = bounds.size.height - previousLocation.y;
 } else {
  location = [touch locationInView:self];
     location.y = bounds.size.height - location.y;
  previousLocation = [touch previousLocationInView:self];
  previousLocation.y = bounds.size.height - previousLocation.y;
 }
  
 // Render the stroke
    if (!lyArr) {
        lyArr = [NSMutableArray array];
    }
    [lyArr addObject:[[LYPoint alloc] initWithCGPoint:previousLocation]];
    [lyArr addObject:[[LYPoint alloc] initWithCGPoint:location]];

    
 [self renderLineFromPoint:previousLocation toPoint:location];
}

// Handles the end of a touch event when the touch is a tap.
- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
 CGRect    bounds = [self bounds];
 UITouch*  touch = [[event touchesForView:self] anyObject];
 if (firstTouch) {
  firstTouch = NO;
  previousLocation = [touch previousLocationInView:self];
  previousLocation.y = bounds.size.height - previousLocation.y;
  [self renderLineFromPoint:previousLocation toPoint:location];
 }
}

// Handles the end of a touch event.
- (void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
 // If appropriate, add code necessary to save the state of the application.
 // This application is not saving state.
    NSLog(@"cancell");
}

運動軌跡

通過把起點到終點的軌跡分解成若干個點,分別來繪制每個點,從而達(dá)到線的效果。
count = MAX(ceilf(sqrtf((end.x - start.x) * (end.x - start.x) + (end.y - start.y) * (end.y - start.y)) / kBrushPixelStep), 1);
這行代碼是核心思想,分出count個點。
然后通過glDrawArrays(GL_POINTS, 0, (int)vertexCount);繪制。

// Drawings a line onscreen based on where the user touches
- (void)renderLineFromPoint:(CGPoint)start toPoint:(CGPoint)end
{
 static GLfloat*  vertexBuffer = NULL;
 static NSUInteger vertexMax = 64;
 NSUInteger   vertexCount = 0,
      count,
      i;
 
 [EAGLContext setCurrentContext:context];
 glBindFramebuffer(GL_FRAMEBUFFER, viewFramebuffer);
 
 // Convert locations from Points to Pixels
 CGFloat scale = self.contentScaleFactor;
 start.x *= scale;
 start.y *= scale;
 end.x *= scale;
 end.y *= scale;
 
 // Allocate vertex array buffer
 if(vertexBuffer == NULL)
  vertexBuffer = malloc(vertexMax * 2 * sizeof(GLfloat));
 
 // Add points to the buffer so there are drawing points every X pixels
 count = MAX(ceilf(sqrtf((end.x - start.x) * (end.x - start.x) + (end.y - start.y) * (end.y - start.y)) / kBrushPixelStep), 1);
 for(i = 0; i < count; ++i) {
  if(vertexCount == vertexMax) {
   vertexMax = 2 * vertexMax;
   vertexBuffer = realloc(vertexBuffer, vertexMax * 2 * sizeof(GLfloat));
  }
  
  vertexBuffer[2 * vertexCount + 0] = start.x + (end.x - start.x) * ((GLfloat)i / (GLfloat)count);
  vertexBuffer[2 * vertexCount + 1] = start.y + (end.y - start.y) * ((GLfloat)i / (GLfloat)count);
  vertexCount += 1;
 }
    
 // Load data to the Vertex Buffer Object
 glBindBuffer(GL_ARRAY_BUFFER, vboId);
 glBufferData(GL_ARRAY_BUFFER, vertexCount*2*sizeof(GLfloat), vertexBuffer, GL_DYNAMIC_DRAW);
 
    glEnableVertexAttribArray(ATTRIB_VERTEX);
    glVertexAttribPointer(ATTRIB_VERTEX, 2, GL_FLOAT, GL_FALSE, 0, 0);
 
 // Draw
    glUseProgram(program[PROGRAM_POINT].id);
 glDrawArrays(GL_POINTS, 0, (int)vertexCount);
 
 // Display the buffer
 glBindRenderbuffer(GL_RENDERBUFFER, viewRenderbuffer);
 [context presentRenderbuffer:GL_RENDERBUFFER];
}

模糊點的效果

點模糊的效果通過開啟混合模式,并設(shè)置混合函數(shù)

// Enable blending and set a blending function appropriate for premultiplied alpha pixel data
    glEnable(GL_BLEND);
    glBlendFunc(GL_ONE, GL_ONE_MINUS_SRC_ALPHA);

注意color和texture2D的操作符是*,不是+。

uniform sampler2D texture;
varying lowp vec4 color;

void main()
{
 gl_FragColor = color * texture2D(texture, gl_PointCoord);
}

最后

送上一張圖

畫圖.gif

附上源碼

思考題

  • 如何改動開頭的加油?
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容