def __init__(self,parent,width,height): self.__parent = parent self.__width = width self.__height = height # 准备surface和ctx self.__surface = cairo.ImageSurface( cairo.FORMAT_ARGB32, width, height) self.__ctx = cairo.Context(self.__surface) self.__ctx.set_antialias(cairo.ANTIALIAS_SUBPIXEL) self.__ctx.scale(self.__width, self.__height) self.__ctx.translate(0.5, 0.5) self.__blackPat = cairo.SolidPattern(0,0,0) self.__whitePat = cairo.SolidPattern(1,1,1) self.__bagua = dict() self.__bagua["qian"] = (-math.pi / 2, (True, True, True)) self.__bagua["xu"] = (-math.pi / 4, (True, True, False)) self.__bagua["kan"] = (0, (False, True, False)) self.__bagua["gen"] = (math.pi / 4, (True, False, False)) self.__bagua["kun"] = (math.pi / 2, (False, False, False)) self.__bagua["zhen"] = (3 * math.pi / 4, (False, False, True)) self.__bagua["li"] = (math.pi, (True, False, True)) self.__bagua["dui"] = (5 * math.pi / 4, (False, True, True))
def __create_icon(self, color): """Создаёт и возвращает экземпляр GdkPixbuf.Pixbuf заданного цвета. color - значение цвета в виде строки "#RRGGBB".""" _ok, gclr = Gdk.Color.parse(color) gclr = gclr.to_floats() csurf = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.iconSizePx, self.iconSizePx) cc = cairo.Context(csurf) #cc.scale(iconSize, iconSize) center = self.iconSizePx / 2.0 radius = center * 0.7 circle = 2 * pi cc.set_source(cairo.SolidPattern(0.0, 0.0, 0.0)) cc.arc(center, center, radius, 0.0, circle) cc.fill() radius1 = radius - 1.0 cc.set_source(cairo.SolidPattern(*gclr)) cc.arc(center, center, radius1, 0.0, circle) cc.fill() return Gdk.pixbuf_get_from_surface(csurf, 0, 0, self.iconSizePx, self.iconSizePx)
def draw_lamp(x, y, width, height, color_main, color_dark): """Draw a lamp from the ceiling.""" if color_main is None: return wireframe_color = saturate(lighten(color_dark, -0.5), -0.3) glass_color = opaque(lighten(color_main, 0), -0.7) light_color = lighten(color_main, 0.5) # light yl = y + height * 3 / 4 r = width * 0.8 pattern = cairo.RadialGradient(x, yl, 0, x, yl, r) pattern.add_color_stop_rgba(0, *lighten(light_color, 1)) pattern.add_color_stop_rgba(0.2, *light_color) pattern.add_color_stop_rgba(1, *opaque(light_color, -1)) ctx.set_source(pattern) ctx.rectangle(x - r, yl - r, r * 2, r * 2) ctx.fill() # mount ctx.set_source(cairo.SolidPattern(*wireframe_color)) draw_path(ctx, ( (x - width / 8, y), (x + width / 8, y), (x, y - r), )) ctx.fill() ctx.rectangle(x - width / 16, y, width / 8, height / 2) ctx.fill() # top r = abs(width / 2) ctx.arc(x, y + height / 2 + r, r, math.pi, 0) ctx.fill() # body pattern = cairo.LinearGradient(x - r, y, x + r, y) pattern.add_color_stop_rgba(0.03, *wireframe_color) pattern.add_color_stop_rgba(0.125, *glass_color) pattern.add_color_stop_rgba(0.27, *wireframe_color) pattern.add_color_stop_rgba(0.5, *glass_color) pattern.add_color_stop_rgba(0.73, *wireframe_color) pattern.add_color_stop_rgba(0.855, *glass_color) pattern.add_color_stop_rgba(0.97, *wireframe_color) ctx.set_source(pattern) ctx.rectangle(x - r, y + height / 2 + r, r * 2, height / 2 - r * 2) ctx.fill() # bottom ctx.set_source(cairo.SolidPattern(*wireframe_color)) draw_path(ctx, ( (x - r, y + height - r), (x + r, y + height - r), (x, y + height + r * 0.4), )) ctx.fill()
def display_day(self, requested_date: date, ctx, x, y, w, h, dp_day=True, day_height=0.05): if dp_day: pat = cairo.SolidPattern(*timetable2.tools.WHITE) ctx.rectangle(x, y, w, day_height) ctx.set_source(pat) ctx.fill() day = requested_date.strftime('%a') ctx.set_source_rgb(0, 0, 0) ctx.set_font_size(0.02) ctx.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) ctx.move_to(x + 0.2 * w, y + 0.5 * day_height) ctx.show_text(day) return self.display_day(requested_date, ctx, x, y + day_height, w, h - day_height, False) meetings = self.get_meeting_at(requested_date) nb_meetings = len(meetings) if nb_meetings > 0: w_meeting = w h_meeting = h / nb_meetings # TODO : What you did is stupid. Change that. for index, meeting in enumerate(meetings): date_begin = meeting.date_begin begin = meeting.date_begin.hour + meeting.date_begin.minute / 60 h_meeting = meeting.get_duration_in_hour() / 24 yloc = y + (begin / 24) * h xloc = x self.display_meeting(meeting, ctx, xloc, yloc, w_meeting, h * h_meeting) else: pat = cairo.SolidPattern(*timetable2.tools.BLACK) ctx.rectangle(x, y, w, h) ctx.set_source(pat) ctx.fill()
def vkb_make_pattern(cr, x, y, w, h, type): if type == VKB_GRADIENT: pattern = cairo.LinearGradient(x, y, x + w, y + h) pattern.add_color_stop_rgb(0, _lighter(cr[0]), _lighter(cr[1]), _lighter(cr[2])) pattern.add_color_stop_rgb(1, _darker(cr[0]), _darker(cr[1]), _darker(cr[2])) elif type == VKB_SOLID: pattern = cairo.SolidPattern(cr[0], cr[1], cr[2]) else: print "Unknown fill pattern." pattern = cairo.SolidPattern(cr[0], cr[1], cr[2]) return pattern
def init_render(fctx): hue = fctx.get_editor_value("Hue") hr, hg, hb, alpha = hue fctx.set_data_obj("hue_tuple", hue) color_array = list(hue) ball_colors = [] color_mult = 1.05 for i in range(0, 10): array = np.array(color_array) * color_mult r, g, b, a = array ball_colors.append( cairo.SolidPattern(_clamp(r), _clamp(g), _clamp(b), 1.0)) color_array = array fctx.set_data_obj("ball_colors", ball_colors) ball_data = [] number_of_balls = fctx.get_editor_value("Number of Balls") speed = fctx.get_editor_value("Speed") speed_var_size_precentage = fctx.get_editor_value("Speed Variation %") for i in range(0, number_of_balls): path_pos = random.uniform(0.0, 1.0) y = random.randint(-330, 1080 + 330) speed_var = random.uniform(-1.0, 1.0) speed_var_size = speed * (speed_var_size_precentage / 100.0) ball_speed = speed + (speed_var * speed_var_size) # fctx.log_line("ball speed: " + str(ball_speed) + " " + str(speed_var_size)) color_index = random.randint(0, 9) ball_data.append((path_pos, y, ball_speed, color_index)) fctx.set_data_obj("ball_data", ball_data)
def draw_all_invaders(): ''' Draws all possible invader configurations, all 32768 of them :return: none ''' count = 0 # used for progress bar total = 2**15 # used for progress bar xpos = 0 ypos = 0 sorted_invaders = generate_sorted_invaders() for invader in sorted_invaders: invader_draw = invader.reshape((5, 5)) # reshape to 5x5 rank = int(np.sum(invader_draw[:, :3])) # determine rank ctx.set_source( cairo.SolidPattern(*(np.array(color2rgb_int[rank]) / 255))) # set color by rank draw_invader(invader_draw, xpos, ypos) # draw call xpos = xpos + 6 * box_width count = count + 1 perc = round(count / total, 4) * 100 # Progress bar if perc % 1 == 0: print('Percent complete: ' + str(perc) + '%') if xpos >= WIDTH: # move to next print row, stay within window limits xpos = 0 ypos = ypos + 6 * box_width
def test_pattern(): with pytest.raises(TypeError): cairo.Pattern() r, g, b, a = 0.1, 0.2, 0.3, 0.4 p = cairo.SolidPattern(r, g, b, a) assert p.get_rgba() == (r, g, b, a) assert not p == object() hash(p) with pytest.raises(TypeError): cairo.Gradient() x0, y0, x1, y1 = 0.0, 0.0, 0.0, 1.0 p = cairo.LinearGradient(x0, y0, x1, y1) assert p.get_linear_points() == (x0, y0, x1, y1) p.add_color_stop_rgba(1, 0, 0, 0, 1) p.add_color_stop_rgba(0, 1, 1, 1, 1) cx0, cy0, radius0, cx1, cy1, radius1 = 1.0, 1.0, 1.0, 2.0, 2.0, 1.0 p = cairo.RadialGradient(cx0, cy0, radius0, cx1, cy1, radius1) assert p.get_radial_circles() == (cx0, cy0, radius0, cx1, cy1, radius1) p.add_color_stop_rgba(0, 1, 1, 1, 1) p.add_color_stop_rgba(1, 0, 0, 0, 1)
def fillWhiteBackground(self, cr, width, height): cr.save() pat = cairo.SolidPattern(1.0, 1.0, 1.0) cr.rectangle(0, 0, width, height) cr.set_source(pat) cr.fill() cr.restore()
def __init__(self, choice): self.choice = choice self.boxes = {} self.uuid = uuid4().hex # get longest text texts = [option.text for (key, option) in choice.options.items()] if choice.draw_prompt: texts.insert(0, choice.prompt) longest_text = max(texts, key=len) x = choice.x y = choice.y dy = choice.dy dx = choice.dx fill = cairo.SolidPattern(*choice.fill) stroke = choice.stroke if choice.draw_prompt: self.boxes['prompt'] = ChoiceBox(choice.prompt, fill, stroke, x, y, False, longest_text, 1920, 1080) y += dy x += dx for name, option in choice.options.items(): self.boxes[name] = ChoiceBox(option.text, fill, stroke, x, y, True, longest_text, 1920, 1080) y += dy x += dx
def rgba(self): a = self.pop() b = self.pop() g = self.pop() r = self.pop() self.require(self.peek(0), VirtualContext) self.push(cairo.SolidPattern(r, g, b, a))
def draw_date(x, y, w, h, color, ctx): if y + h > 0.5: print("ay") pat = cairo.SolidPattern(*color) ctx.rectangle(x, y, w, h) ctx.set_source(pat) ctx.fill()
def unpack_cairo_pattern(value): red, green, blue, alpha = unpack_color(value) return cairo.SolidPattern( red / 65535.0, green / 65535.0, blue / 65535.0, alpha / 65535.0)
def render_frame(frame, fctx, w, h): # Frame Render code here cr = fctx.get_frame_cr() bg_color = cairo.SolidPattern(*fctx.get_data_obj("hue_tuple")) ball_colors = fctx.get_data_obj("ball_colors") ball_data = fctx.get_data_obj("ball_data") cr.set_source(bg_color) cr.rectangle(0, 0, w, h) cr.fill() size = 330.0 xc = size / 2.0 yc = size / 2.0 number_of_balls = fctx.get_editor_value("Number of Balls") path_start_x = -size path_end_x = w + size path_len = path_end_x - path_start_x SPEED_NORM_PER_FRAME = 15.0 / float(w) for i in range(0, number_of_balls): path_pos, y, ball_speed, color_index = ball_data[i] #fctx.log_msg(str(i) + " " + str(x)) xpos_norm = path_pos + (float(frame) * ball_speed * SPEED_NORM_PER_FRAME) while xpos_norm > 1.0: xpos_norm = xpos_norm - 1.0 x = path_start_x + path_len * xpos_norm cr.save() cr.translate(x, y) cr.arc(xc, yc, size / 4.0, 0.0, 2.0 * math.pi) cr.set_source(ball_colors[color_index]) cr.fill() cr.restore()
def background(self, colour): """ Create canvas background. """ pat = cairo.SolidPattern(*colour) self.ctx.rectangle(0, 0, 1, 1) self.ctx.set_source(pat) self.ctx.fill()
def test_pattern(self): pattern = cairo.SolidPattern(1, 1, 1, 1) result = self.pass_object_through_signal(pattern, self.tester.sig_pattern) self.assertTrue(isinstance(result, cairo.Pattern)) self.assertTrue(isinstance(result, cairo.SolidPattern)) with pytest.raises(TypeError): result = self.pass_object_through_signal(object(), self.tester.sig_pattern)
def draw(cr, width, height): cr.scale(width, height) cr.set_line_width(0.04) cr.rectangle(0.1, 0.1, 0.6, 0.6) cr.set_line_width(0.03) cr.set_source_rgb(0.8, 0.8, 0.8) cr.fill() cr.push_group() cr.rectangle(0.3, 0.3, 0.6, 0.6) cr.set_source(cairo.SolidPattern(1, 0, 0)) cr.fill_preserve() cr.set_source(cairo.SolidPattern(0, 0, 0)) cr.stroke() cr.pop_group_to_source() cr.paint_with_alpha(0.5)
def color_for(x): if x < 0.1: intensity = 0 else: intensity = (1.0 * x / max_rate)**0.8 h = intensity * 0.5 s = 1.0 l = 0.3 + intensity * 0.5 r, g, b = colorsys.hls_to_rgb(h, l, s) return cairo.SolidPattern(r, g, b, 1.0)
def render_frame(frame, fctx, w, h): cr = fctx.get_frame_cr() bg_color = cairo.SolidPattern(*fctx.get_data_obj("hue_tuple")) color_positions = fctx.get_data_obj("color_positions") size = fctx.get_editor_value("Size") points = fctx.get_data_obj("points") middle_hues = fctx.get_data_obj("middle_hues") color_positions = fctx.get_data_obj("color_positions") deltas = fctx.get_data_obj("deltas") x0 = -size / 2.0 y0 = -size / 2.0 hue_change_anim_range = 0.1 cr.set_source(bg_color) cr.rectangle(0, 0, w, h) cr.fill() fctx.log_line("erer" + str(len(middle_hues)) + ", " + str(rows)) for row in range(0, rows): yt = y0 + shape_height * row x_row = x0 + shape_width / 2.0 * (float(row) % 2.0) for col in range(0, cols): index = row * cols + col # get color for hex r, g, b = middle_hues[index] color_position = color_positions[index] delta = deltas[index] r = _clamp(r + color_position * hue_change_anim_range) g = _clamp(g + color_position * hue_change_anim_range) b = _clamp(g + color_position * hue_change_anim_range) # animate color color_position = color_position + delta color_positions[index] = color_position if abs(color_position) > 1.0: delta = -delta deltas[index] = delta # draw hex xt = x_row + shape_width * col cr.save() cr.translate(xt, yt) x, y = _point_mult(size, *points[0]) cr.move_to(x, y) for i in range(1, 6): x, y = _point_mult(size, *points[i]) cr.line_to(x, y) cr.close_path() cr.set_source_rgb(r, g, b) cr.fill() cr.restore()
def display_meeting(self, meeting, ctx, x, y, w, h, dp_label=False): if meeting.labels[0].name == "Other": pat = cairo.SolidPattern(*Meeting.locations_color[meeting.loc_id]) else: pat = cairo.SolidPattern(*meeting.labels[0].color) ctx.rectangle(x, y, w, h) ctx.set_source(pat) ctx.fill() if (dp_label): ctx.set_source_rgb(0, 0, 0) ctx.set_font_size(0.03) ctx.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) ctx.move_to(x + w * 0.2, y + h * 0.5) ctx.show_text(meeting.labels[0].name)
def make(qrcode, surface, pixelsize, offset): ctx = cairo.Context(surface) pat_w = cairo.SolidPattern(1, 1, 1, 1) pat_b = cairo.SolidPattern(0, 0, 0, 1) ctx.rectangle(0, 0, pixelsize, pixelsize) ctx.set_source(pat_w)#fill it white ctx.fill() ctx.set_source(pat_b)#paint it black for r in range(qrcode.modules_count): for c in range(qrcode.modules_count): if qrcode.modules[r][c]: x = (c + offset) * qrcode.box_size y = (r + offset) * qrcode.box_size #cairo Rectangle is x0, y0, x1, y1 x1, y1 = (qrcode.box_size, qrcode.box_size) ctx.rectangle(x, y, x1, y1) ctx.fill() return surface
def _get_cell_background(self, index): """Get the background colour to use for the given cell.""" if index == self._current_cell: # Currently selected cell. return cairo.SolidPattern(0.541, 0.886, 0.204) # green elif (self._show_hints and self._current_cell != (-1, -1) and (self._current_cell[1] == 0 or self._current_cell[1] == self._current_cell[0]) and (index[1] == 0 or index[1] == index[0])): # Hint all edge cells if the currently selected cell is on an edge. return cairo.SolidPattern(0.447, 0.624, 0.812) # blue elif (self._show_hints and index[0] == self._current_cell[0] - 1 and (index[1] == self._current_cell[1] - 1 or index[1] == self._current_cell[1])): # Hint the two cells above the currently selected cell. return cairo.SolidPattern(0.988, 0.914, 0.310) # yellow else: # Non-selected, normal cell background. return cairo.SolidPattern(1.0, 1.0, 1.0) # white
def parse(self, text): # TBD, other color formats if not len(text) == 8: raise ValueError("Could not parse as color: " + text) a = int(text[0:2], 16) / 0xFF r = int(text[2:4], 16) / 0xFF g = int(text[4:6], 16) / 0xFF b = int(text[6:8], 16) / 0xFF return cairo.SolidPattern(r, g, b, a)
def __init__(self): super(Viewport, self).__init__() self.add_events(gtk.gdk.POINTER_MOTION_MASK | gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.SCROLL_MASK) self.connect('expose-event', self._on_expose) self.connect('scroll-event', self._on_scroll) self.connect('button-press-event', self._on_button_press) self.connect('button-release-event', self._on_button_release) self.connect('motion-notify-event', self._on_motion_notify) self.bgpattern = cairo.SolidPattern(0.1, 0.1, 0.1)
def draw_poly(ctx, coords, color, line_width=1, outline_darken=0): """Draw a single brick.""" ctx.set_source(cairo.SolidPattern(*color)) draw_path(ctx, coords) ctx.fill() if not outline_darken: return ctx.set_line_width(line_width) ctx.set_source_rgba(*lighten(color, -outline_darken)) draw_path(ctx, coords) ctx.stroke()
def drawLabel(self, ctx, alpha): self.Save(ctx) # 设置字体 ctx.set_font_face(self.__fontface) ctx.set_font_size(0.5) # 计算 label = self.get_label() (x, y, width, height, dx, dy) = ctx.text_extents(label) ctx.set_source(cairo.SolidPattern(0, 0, 0, alpha)) ctx.move_to(-width / 2, height / 2) ctx.show_text(label) self.Restore(ctx)
def display_line(self, dates, ctx, x, y, w, h, timestamp=True, timestamp_width=0.1): if timestamp: pat = cairo.SolidPattern(*timetable2.tools.WHITE) ctx.rectangle(x, y, timestamp_width, h) ctx.set_source(pat) ctx.fill() h -= 0.05 # C'est sale Pierre, pas bien times = timetable2.tools.time_range() nb_times = len(times) w_time = timestamp_width h_time = h / nb_times for index, time in enumerate(times): xloc = x yloc = y + index * h_time ctx.set_source_rgb(0, 0, 0) ctx.set_font_size(0.017) ctx.select_font_face("Arial", cairo.FONT_SLANT_NORMAL, cairo.FONT_WEIGHT_NORMAL) ctx.move_to(xloc + 0.2 * w_time, yloc + 0.7 * h_time + 0.05) ctx.show_text(time) h += 0.05 return self.display_line(dates, ctx, x + w_time, y, w - w_time, h, False) nb_dates = len(dates) w_day = w if nb_dates > 0: w_day = w / nb_dates h_day = h for index, requested_date in enumerate(dates): xloc = x + w_day * index yloc = y self.display_day(requested_date, ctx, xloc, yloc, w_day, h_day)
def draw_polygon(n, center, r, color, rotation=0, fill=False): ''' Draws regular polygon :param n: number of polygon sides :param center: center of the polygon :param r: radius :param color: color in RGB fraction format [R, G, B] :param fill: if you want to fill in the shape :return: ''' verts = regular_polygon(n, center, r, rotation) ctx.set_source(cairo.SolidPattern(*color)) draw_shape(verts) if fill: ctx.close_path() ctx.fill() ctx.stroke()
def draw_marker(x, h, msg, col=(1, 0, 0), ang=0.5): p1 = getpos(x, h) ctx.new_path() ctx.set_source(cairo.SolidPattern(*col)) ctx.arc(p1[0], p1[1], 6, 0, 2 * math.pi) ctx.fill() ctx.new_path() ctx.save() ctx.translate(*p1) ctx.rotate(-ang) ctx.set_font_size(17) ctx.move_to(15, 0) ctx.show_text(msg) ctx.restore()
def _set_style(self, x, y, **args): #print "new path",x,y,args self._ctx.save() self._ctx.new_path() self._ctx.move_to(x, y) if 'color' in args: self._ctx.set_source_rgba(*_color(args['color'])) if 'delta_color' in args: self._ctx.set_source_rgba( *delta_color(args['color'], int(args['delta_color']))) if 'linewidth' in args: self._ctx.set_line_width(args['linewidth']) if 'fillcolor' in args: pattern = cairo.SolidPattern(*_color(args['fillcolor'])) self._ctx.set_source(pattern) if 'weight' in args or 'style' in args: w = self._weights.get(args.get('weight'), cairo.FONT_WEIGHT_NORMAL) s = self._slants.get(args.get('style'), cairo.FONT_SLANT_NORMAL) face = self._ctx.select_font_face("sans-serif", s, w) if 'size' in args: self._ctx.set_font_size(args['size'])