Skip to content

Instantly share code, notes, and snippets.

@giann
Created January 14, 2019 07:46
Show Gist options
  • Save giann/fd05b9b0ace3aa44be91394e4491c336 to your computer and use it in GitHub Desktop.
Save giann/fd05b9b0ace3aa44be91394e4491c336 to your computer and use it in GitHub Desktop.
#include <SDL2/SDL.h>
#include <cairo/cairo.h>
#include <math.h>
void draw(cairo_t *cr) {
cairo_text_extents_t extents;
const char *utf8 = "cairo";
// Hello world cairo
double x, y;
cairo_select_font_face(cr, "Sans",
CAIRO_FONT_SLANT_NORMAL,
CAIRO_FONT_WEIGHT_NORMAL);
cairo_set_font_size(cr, 100.0);
cairo_text_extents(cr, utf8, &extents);
x = 0;
y = 0;
cairo_move_to(cr, x, y);
cairo_show_text(cr, utf8);
/* draw helping lines */
cairo_set_source_rgba(cr, 1, 0.2, 0.2, 0.6);
cairo_set_line_width(cr, 6.0);
cairo_arc(cr, x, y, 10.0, 0, 2*M_PI);
cairo_fill(cr);
cairo_move_to(cr, x, y);
cairo_rel_line_to(cr, 0, -extents.height);
cairo_rel_line_to(cr, extents.width, 0);
cairo_rel_line_to(cr, extents.x_bearing, -extents.y_bearing);
cairo_stroke(cr);
}
int main(int argc, char const *argv[]) {
SDL_Window *window;
SDL_Renderer *renderer;
SDL_Event event;
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
SDL_LogError(
SDL_LOG_CATEGORY_APPLICATION,
"Couldn't initialize SDL: %s",
SDL_GetError());
return 3;
}
if (SDL_CreateWindowAndRenderer(
320,
240,
SDL_WINDOW_RESIZABLE,
&window,
&renderer)) {
SDL_LogError(
SDL_LOG_CATEGORY_APPLICATION,
"Couldn't create window and renderer: %s",
SDL_GetError());
return 3;
}
SDL_Texture *texture = SDL_CreateTexture(
renderer,
SDL_PIXELFORMAT_ARGB32,
SDL_TEXTUREACCESS_STREAMING,
320, 240);
if (!texture) {
SDL_LogError(
SDL_LOG_CATEGORY_APPLICATION,
"Couldn't create texture: %s",
SDL_GetError());
return 3;
}
void *pixels;
int pitch;
cairo_surface_t *surface = cairo_image_surface_create_for_data(
(unsigned char *)pixels,
CAIRO_FORMAT_ARGB32,
320, 240, pitch);
cairo_t *cr = cairo_create(surface);
SDL_LockTexture(texture, nullptr, &pixels, &pitch);
draw(cr);
while (1) {
SDL_PollEvent(&event);
if (event.type == SDL_QUIT) {
break;
}
SDL_RenderClear(renderer);
SDL_RenderCopy(renderer, texture, nullptr, nullptr);
SDL_RenderPresent(renderer);
}
SDL_UnlockTexture(texture);
cairo_destroy(cr);
cairo_surface_destroy(surface);
SDL_DestroyTexture(texture);
SDL_DestroyRenderer(renderer);
SDL_DestroyWindow(window);
SDL_Quit();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment