def move(self, command): logging.debug('move') # Grab the current contents of the surface pattern = cairo.SurfacePattern(self.surface) surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.surface.get_width(), self.surface.get_height()) context = cairo.Context(surface) context.set_source(pattern) context.paint() pattern = cairo.SurfacePattern(surface) moveMatrix = cairo.Matrix() moveMatrix.scale( float(surface.get_width()) / self.hatSize, -float(surface.get_height()) / self.hatSize) moveMatrix.translate(-1, -(self.hatSize + 1)) logmatrix(logging.debug, moveMatrix) if command.startswith('up'): moveMatrix.translate(0, -1) logmatrix(logging.debug, moveMatrix) pattern.set_matrix(moveMatrix) self.context.set_source(pattern) self.context.paint() self.context.set_source_rgba(0, 0, 0) self.context.rectangle(1, 1, self.hatSize, 1) self.context.fill() elif command.startswith('down'): moveMatrix.translate(0, 1) logmatrix(logging.debug, moveMatrix) pattern.set_matrix(moveMatrix) self.context.set_source(pattern) self.context.paint() self.context.set_source_rgba(0, 0, 0) self.context.rectangle(1, self.hatSize, self.hatSize, 1) self.context.fill() elif command.startswith('left'): moveMatrix.translate(1, 0) logmatrix(logging.debug, moveMatrix) pattern.set_matrix(moveMatrix) self.context.set_source(pattern) self.context.paint() self.context.set_source_rgba(0, 0, 0) self.context.rectangle(self.hatSize, 1, 1, self.hatSize) self.context.fill() elif command.startswith('right'): moveMatrix.translate(-1, 0) logmatrix(logging.debug, moveMatrix) pattern.set_matrix(moveMatrix) self.context.set_source(pattern) self.context.paint() self.context.set_source_rgba(0, 0, 0) self.context.rectangle(1, 1, 1, self.hatSize) self.context.fill() else: return self.update()
def draw(self, ctx): # Check for the type of the image object (rsvg, surface, pixbuf) # Draw accordingly if self.imgobj != None: if self.transparency < 0: self.transparency = 0 elif self.transparency > 1: self.transparency = 1 if self.transparency < self.transparency_orig: self.transparency = self.transparency_orig #print " * " + self.categ + " " + self.type + ": draw(x="+str(self.x)+", y="+str(self.y)+", w="+str(self.width)+", h="+str(self.height)+", transparency="+str(self.transparency)+")" if self.image_type == "rsvg": size=self.imgobj.get_dimension_data() if size: # Copy the svg to a cairo surface if not self.width: self.width = size[0] if not self.height: self.height = size[1] png_surface = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width, self.height) ctx_tmp = cairo.Context(png_surface) self.imgobj.render_cairo(ctx_tmp) # Draw the new surface pattern = cairo.SurfacePattern(png_surface) matrix = cairo.Matrix() if self.width and self.height: iw = float(size[2]) ih = float(size[3]) matrix.scale(iw/self.width, ih/self.height) matrix.translate(-self.x, -self.y) pattern.set_matrix(matrix) ctx.set_source(pattern) if self.can_fade: ctx.paint_with_alpha(1-self.transparency) else: ctx.paint() elif self.image_type == "surface": # Draw cairo surface pattern = cairo.SurfacePattern(self.imgobj) matrix = cairo.Matrix() if self.width and self.height: iw = float(self.imgobj.get_width()) ih = float(self.imgobj.get_height()) matrix.scale(iw/self.width, ih/self.height) matrix.translate(-self.x, -self.y) pattern.set_matrix(matrix) ctx.set_source(pattern) if self.can_fade: ctx.paint_with_alpha(1-self.transparency) else: ctx.paint() elif self.image_type == "pixbuf": # Draw pixbuf ctx.save() pw = float(self.imgobj.get_width()) ph = float(self.imgobj.get_height()) ctx.translate(self.x, self.y) pixscaled = self.imgobj if self.width and self.height: pixscaled = self.imgobj.scale_simple(self.width,self.height,1) ctx.set_source_pixbuf(pixscaled, 0, 0) if self.can_fade: ctx.paint_with_alpha(1-self.transparency) else: ctx.paint() ctx.restore()
def fetch_tile(self, scale, bx, by, extra = 0): """Fetches a tile, given a scale (Multiplication of original dimensions.) and base coordinates (bx, by) - the tile will be the size provided on class initialisation. This request is going through a caching layer, which will hopefuly have the needed tile. If not it will be generated and the tile that has been used the least recently thrown away.""" # Instance the key for this tile and check if it is in the cache, if so grab it, rearrange it to the top of the queue and return it... key = (scale, bx, by, self.interpolate) if key in self.cache: ret = self.cache[key] del self.cache[key] self.cache[key] = ret return ret # Select a new tile to render into - either create one or recycle whatever is going to die at the end of the cache... if len(self.cache)>=(self.cache_size-extra): ret = self.cache.popitem()[1] else: ret = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.tile_size, self.tile_size) # Render the tile, with the appropriate scaling... ctx = cairo.Context(ret) ctx.save() ctx.set_operator(cairo.OPERATOR_SOURCE) ctx.set_source_rgba(1.0, 1.0, 1.0, 0.0) ctx.paint() ctx.restore() if scale<8.0: oasp = cairo.SurfacePattern(self.original) oasp.set_filter(cairo.FILTER_BILINEAR if self.interpolate else cairo.FILTER_NEAREST) ctx.translate(-bx, -by) ctx.scale(scale, scale) ctx.set_source(oasp) ctx.paint() else: # Cairo has an annoying habit of failing if you push the scale too far - this makes it recursive for such situations... power = math.log(scale) / math.log(2.0) child_scale = 2**(int(math.floor(power))-2) remain_scale = scale / child_scale child_bx = int(math.floor((bx-1) / (remain_scale*0.5*self.tile_size))) * self.tile_size//2 child_by = int(math.floor((by-1) / (remain_scale*0.5*self.tile_size))) * self.tile_size//2 child = self.fetch_tile(child_scale, child_bx, child_by, extra+1) oasp = cairo.SurfacePattern(child) oasp.set_filter(cairo.FILTER_BILINEAR if self.interpolate else cairo.FILTER_NEAREST) ctx.translate(-(bx - child_bx*remain_scale), -(by - child_by*remain_scale)) ctx.scale(remain_scale, remain_scale) ctx.set_source(oasp) ctx.paint() # Store the tile in the cache and return... self.cache[key] = ret return ret
def toggle_preview(self, widget, data=None): if widget.get_active(): # Insert a tag with ID to scroll to self.TextBuffer.insert_at_cursor('<span id="scroll_mark"></span>') args = [ 'pandoc', '--from=markdown', '--smart', '-thtml', '--mathjax', '-c', helpers.get_media_file('uberwriter.css') ] p = subprocess.Popen(args, stdin=subprocess.PIPE, stdout=subprocess.PIPE) text = bytes(self.get_text(), "utf-8") output = p.communicate(text)[0] # Load in Webview and scroll to #ID self.webview = WebKit.WebView() self.webview.load_html_string(output.decode("utf-8"), 'file://localhost/' + '#scroll_mark') # Delete the cursor-scroll mark again cursor_iter = self.TextBuffer.get_iter_at_mark( self.TextBuffer.get_insert()) begin_del = cursor_iter.copy() begin_del.backward_chars(30) self.TextBuffer.delete(begin_del, cursor_iter) self.ScrolledWindow.remove(self.TextEditor) self.ScrolledWindow.add(self.webview) self.webview.show() # Making the background white white_background = helpers.get_media_path('white.png') surface = cairo.ImageSurface.create_from_png(white_background) self.background_pattern = cairo.SurfacePattern(surface) self.background_pattern.set_extend(cairo.EXTEND_REPEAT) # This saying that all links will be opened in default browser, but local files are opened in appropriate apps: self.webview.connect("navigation-requested", self.on_click_link) else: self.ScrolledWindow.remove(self.webview) self.webview.destroy() self.ScrolledWindow.add(self.TextEditor) self.TextEditor.show() surface = cairo.ImageSurface.create_from_png(self.background_image) self.background_pattern = cairo.SurfacePattern(surface) self.background_pattern.set_extend(cairo.EXTEND_REPEAT) self.queue_draw()
def create_surpat(self): sr1 = cairo.ImageSurface.create_from_png("blueweb.png") sr2 = cairo.ImageSurface.create_from_png("maple.png") sr3 = cairo.ImageSurface.create_from_png("crack.png") sr4 = cairo.ImageSurface.create_from_png("chocolate.png") self.pt1 = cairo.SurfacePattern(sr1) self.pt1.set_extend(cairo.EXTEND_REPEAT) self.pt2 = cairo.SurfacePattern(sr2) self.pt2.set_extend(cairo.EXTEND_REPEAT) self.pt3 = cairo.SurfacePattern(sr3) self.pt3.set_extend(cairo.EXTEND_REPEAT) self.pt4 = cairo.SurfacePattern(sr4) self.pt4.set_extend(cairo.EXTEND_REPEAT)
def setup_images(self): """ Create image structures for each icon files. """ for img_name, iconfile in self.icons_files.iteritems(): try: img = cairo.ImageSurface.create_from_png(iconfile) except cairo.Error: self.qtile.log.exception('No icon found for application ' + img_name + '(' + iconfile + ')') return input_width = img.get_width() input_height = img.get_height() sp = input_height / float(self.bar.height - 4) width = input_width / sp if width > self.width: self.width = int(width) + self.padding * 2 imgpat = cairo.SurfacePattern(img) scaler = cairo.Matrix() scaler.scale(sp, sp) scaler.translate(self.padding * -1, -2) imgpat.set_matrix(scaler) imgpat.set_filter(cairo.FILTER_BEST) self.surfaces[img_name] = imgpat self.icons_widths[img_name] = width
def svg2png(svgFile): svg = rsvg.Handle(file=svgFile) #This block converts the svg to png and applies naming conventions imgWidth=svg.props.width imgHeight=svg.props.height img = cairo.ImageSurface(cairo.FORMAT_ARGB32, imgWidth, imgHeight) ctx = cairo.Context(img) handler = rsvg.Handle(svgFile) handler.render_cairo(ctx) # flip x, y pat = cairo.SurfacePattern(img) # another way to flip an image on the Y axis # the order of the translate and scale are important m = cairo.Matrix() m.translate(0, img.get_height()) m.scale(1, -1) pat.set_matrix(m) dest = cairo.ImageSurface(cairo.FORMAT_ARGB32, img.get_width(), img.get_height()) cr = cairo.Context(dest) cr.set_source(pat) cr.paint() dest.write_to_png(svgFile.replace(".svg",".png"))
def draw_pattern(self): w, h = self.get_size() pattern = self.fill[2] surface = cairo.ImageSurface(cairo.FORMAT_RGB24, w, h) ctx = cairo.Context(surface) self.draw_cairo_background(ctx) if self.cms.app.current_doc: cfg = self.cms.app.current_doc.model.config else: cfg = sk2_config.SK2_Config() config_file = os.path.join(self.cms.app.appdata.app_config_dir, 'sk2_config.xml') cfg.load(config_file) image_obj = sk2_model.Pixmap(cfg) hndl = image_obj.handler hndl.load_from_b64str(self.cms, pattern[1]) hndl.flip_left_to_right() if pattern[0] == sk2const.PATTERN_IMG and len(pattern) > 2: image_obj.style[3] = deepcopy(pattern[2]) sp = cairo.SurfacePattern(hndl.get_surface(self.cms)) sp.set_extend(cairo.EXTEND_REPEAT) trafo = [-1.0, 0.0, 0.0, 1.0, 0.0, 0.0] if len(pattern) > 3: trafo = libgeom.multiply_trafo(pattern[3], trafo) pattern_matrix = cairo.Matrix(*trafo) pattern_matrix.invert() sp.set_matrix(pattern_matrix) ctx.set_source(sp) ctx.rectangle(0, 0, w, h) ctx.fill() self.gc_draw_bitmap(wal.copy_surface_to_bitmap(surface), 0, 0)
def gen(self, td): h, w = td[0], td[1] fmt = cairo.Format.ARGB32 stride = fmt.stride_for_width(w) b = bytearray(stride * h * 4) mb = memoryview(b).cast("I") for y in range(h): for x in range(w): addr = (y * stride) + (x * 4) addri = addr // 4 v = td[2 + x + (w * y)] if v == 1: mb[addri] = 0x44444444 elif v == 2: mb[addri] = 0xCCCCCCCC elif v == 3: b[addr] = 128 b[addr + 1] = random.randint(0, 255) b[addr + 2] = random.randint(0, 255) b[addr + 3] = random.randint(0, 255) else: mb[addri] = 0x00000000 thumb = cairo.SurfacePattern( cairo.ImageSurface.create_for_data(b, fmt, w, h)) thumb.set_filter(cairo.Filter.NEAREST) return thumb
def set_mask_pattern(self): """ Prepare mask pattern for cairooverlay. """ source = cairo.ImageSurface.create_from_png('./mosaic.png') self.pattern = cairo.SurfacePattern(source) self.pattern.set_extend(cairo.Extend.REPEAT)
def __draw_tiles(self, which=None, off_x=0, off_y=0): self.delay_expose = False cr = gtk.gdk.CairoContext(cairo.Context(self.cr_drawing_area_map)) if which == None: which = self.surface_buffer.values() for surface, x, y, scale_source in which: if surface == None: print "pbuf was none!" continue size = self.tile_loader.TILE_SIZE if scale_source == None: cr.set_source_surface(surface, x + off_x, y + off_y) else: xs, ys = scale_source imgpat = cairo.SurfacePattern(surface) imgpat.set_filter(cairo.FILTER_BEST) scale = cairo.Matrix() scale.translate(xs, ys) scale.scale(0.5, 0.5) scale.translate(-x + off_x, -y + off_y) imgpat.set_matrix(scale) cr.set_source(imgpat) cr.rectangle(max(0, x + off_x), max(0, y + off_y), min(size + x, size, self.map_width - x + size), min(size + y, size, self.map_height - y + size)) cr.fill() self.queue_draw_area(max(0, x + off_x), max(0, y + off_y), min(size + x, size, self.map_width - x + size), min(size + y, size, self.map_height - y + size)) return False
def dark_mode_toggled(self, widget, data=None): if widget.get_active(): # Dark Mode is on # Hack for f*****g unico-shit if Gtk.get_minor_version() == 4: css = open(helpers.get_media_path('style_dark_old.css'), 'rb') else: css = open(helpers.get_media_path('style_dark.css'), 'rb') css_data = css.read() css.close() self.style_provider.load_from_data(css_data) self.background_image = helpers.get_media_path('bg_dark.png') self.MarkupBuffer.dark_mode(True) else: # Dark mode off css = open(helpers.get_media_path('style.css'), 'rb') css_data = css.read() css.close() self.style_provider.load_from_data(css_data) self.background_image = helpers.get_media_path('bg_light.png') self.MarkupBuffer.dark_mode(False) surface = cairo.ImageSurface.create_from_png(self.background_image) self.background_pattern = cairo.SurfacePattern(surface) self.background_pattern.set_extend(cairo.EXTEND_REPEAT) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), self.style_provider, Gtk.STYLE_PROVIDER_PRIORITY_USER ) (w, h) = self.get_size() self.resize(w+1, h+1)
def addPanel(filename): ctx.save() im1 = cairo.ImageSurface.create_from_png(file(filename, 'r')) # Set origin for this layer ctx.translate(0, 0) imgpat = cairo.SurfacePattern(im1) imh = im1.get_height() imw = im1.get_width() scale_w = imw / w scale_h = imh / h compromise_scale = max(scale_w, scale_h) # Scale source image scaler = cairo.Matrix() scaler.scale(compromise_scale, compromise_scale) imgpat.set_matrix(scaler) imgpat.set_filter(cairo.FILTER_BEST) ctx.set_source(imgpat) ctx.rectangle(0, 0, w, h) ctx.fill() ctx.restore()
def draw_map(self, world_data, turn_data): width = self.drawSize height = self.drawSize surface = cairo.ImageSurface (cairo.FORMAT_ARGB32, width, height) cr = cairo.Context (surface) gdkcr = gtk.gdk.CairoContext (cr) worldmap.draw_map(gdkcr, width, height, world_data, turn_data) self.guiTurn += 1 # Draw the map cairo_context_final = self.map_area.window.cairo_create() pattern = cairo.SurfacePattern(surface) allocation = self.map_area.get_allocation() width = allocation.width height = allocation.height sx = width / float(self.drawSize) sy = height / float(self.drawSize) matrix = cairo.Matrix(xx=sx, yy=sy) cairo_context_final.transform(matrix) cairo_context_final.set_source(pattern) cairo_context_final.paint()
def dark_mode_toggled(self, widget, data=None): # Save state for saving settings later self.dark_mode = widget.get_active() if self.dark_mode: # Dark Mode is on css = open(helpers.get_media_path('style_dark.css'), 'rb') css_data = css.read() css.close() self.style_provider.load_from_data(css_data) self.background_image = helpers.get_media_path('bg_dark.png') self.MarkupBuffer.dark_mode(True) else: # Dark mode off css = open(helpers.get_media_path('style.css'), 'rb') css_data = css.read() css.close() self.style_provider.load_from_data(css_data) self.background_image = helpers.get_media_path('bg_light.png') self.MarkupBuffer.dark_mode(False) surface = cairo.ImageSurface.create_from_png(self.background_image) self.background_pattern = cairo.SurfacePattern(surface) self.background_pattern.set_extend(cairo.EXTEND_REPEAT) Gtk.StyleContext.add_provider_for_screen( Gdk.Screen.get_default(), self.style_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) # Redraw contents of window (self) self.queue_draw()
def draw(self, boxes = None): if not self.img_surface: context = cairo.Context(self.surface) context.set_source_rgb(1, 1, 1) context.set_operator(cairo.OPERATOR_SOURCE) context.paint() else: context = cairo.Context(self.surface) pattern = cairo.SurfacePattern(self.img_surface) pattern.set_filter(cairo.FILTER_GOOD) xscale = float(self.img_surface.get_width()) \ / float(self.surface.get_width()) yscale = float(self.img_surface.get_height()) \ / float(self.surface.get_height()) pattern.set_matrix(cairo.Matrix(xx = xscale, yy = yscale)) context.set_source(pattern) context.set_operator(cairo.OPERATOR_SOURCE) context.paint() context.set_operator(cairo.OPERATOR_OVER) for (gprim, color) in self.gprims: context.set_source_rgb(color.red / float(65535), color.green / float(65535), color.blue / float(65535)) gprim.draw(context) if boxes: context.set_source_rgb(.5, 0, .5) for box in boxes: box.draw(context) print 'drawing ' + str(box) self.queue_draw()
def render_bar(self, w, h): s = cairo.ImageSurface(cairo.FORMAT_ARGB32, w, h) cr = cairo.Context(s) self.render_bar_segments(cr, w, h, h / 2) self.render_bar_strokes(cr, w, h, h / 2) pattern = cairo.SurfacePattern(s) return pattern
def _init_alpha_checks(self): """Initialize the alpha check backgrounds""" # Real: checkerboard pattern, rendered via Cairo assert tiledsurface.N % gui.style.ALPHA_CHECK_SIZE == 0 N = tiledsurface.N size = gui.style.ALPHA_CHECK_SIZE nchecks = int(N / size) cairo_surf = cairo.ImageSurface(cairo.FORMAT_ARGB32, N, N) cr = cairo.Context(cairo_surf) render_checks(cr, size, nchecks) cairo_surf.flush() # Real: MyPaint background surface for layers-but-no-bg rendering pattern = cairo.SurfacePattern(cairo_surf) pattern.set_extend(cairo.EXTEND_REPEAT) self._real_alpha_check_pattern = pattern # Fake: faster rendering, but ugly tile = empty((N, N, 4), dtype='uint16') f = 1 << 15 col1 = [int(f * c) for c in gui.style.ALPHA_CHECK_COLOR_1] + [f] col2 = [int(f * c) for c in gui.style.ALPHA_CHECK_COLOR_2] + [f] tile[:] = col1 for i in xrange(nchecks): for j in xrange(nchecks): if (i+j) % 2 == 0: continue tile[i*size:(i+1)*size, j*size:(j+1)*size] = col2 self._fake_alpha_check_tile = tile
def __expose(self, widget, event): cr = widget.window.cairo_create() x, y, w, h = widget.allocation if self.progress >= 0: surface = cairo.ImageSurface.create_from_png(self.bg_grid_path) surface_pattern = cairo.SurfacePattern(surface) surface_pattern.set_extend(cairo.EXTEND_REPEAT) # Draw picture draw_pixbuf(cr, self.pixbuf, x, y + (h - self.pixbuf.get_height()) / 2) # Draw mask cr.rectangle(x, y, w, self.progress) cr.set_source(surface_pattern) cr.fill() # Draw scanning line. draw_pixbuf(cr, self.scan_line_pixbuf, x, y + self.progress) self.scanning_timeout = gobject.timeout_add( 10, lambda: self.queue_draw()) self.progress -= 1 else: gobject.source_remove(self.scanning_timeout) draw_pixbuf(cr, self.pixbuf, x, y + (h - self.pixbuf.get_height()) / 2) return True
def DrawBitmap(self, bmp, x, y, w=-1, h=-1): """ Draw the bitmap at (x,y). If the width and height parameters are passed then the bitmap is scaled to fit that size. Either a wx.Bitmap or a GraphicsBitmap may be used. """ if isinstance(bmp, wx.Bitmap): bmp = GraphicsBitmap.CreateFromBitmap(bmp) # In case we're scaling the image by using a width and height # different than the bitmap's size, create a pattern # transformation on the surface and draw the transformed # pattern. self.PushState() pattern = cairo.SurfacePattern(bmp.Surface) bw, bh = bmp.Size if w == -1: w = bw if h == -1: h = bh scaleX = w / float(bw) scaleY = h / float(bh) self._context.scale(scaleX, scaleY) self._context.translate(x, y) self._context.set_source(pattern) # use the original size here since the context is scaled already... self._context.rectangle(0, 0, bw, bh) # fill the rectangle with the pattern self._context.fill() self.PopState()
def Apply(self, ctx): # set up the context with this pen's parameters ctx = ctx.GetNativeContext() ctx.set_line_width(self._width) ctx.set_line_cap(self._capMap[self._cap]) ctx.set_line_join(self._joinMap[self._join]) ctx.set_dash([]) if self._style == wx.SOLID: ctx.set_source_rgba(*_colourToValues(self._colour)) elif self._style == wx.STIPPLE: if not self._pattern and self._stipple: # make a pattern from the stipple bitmap img = wx.lib.wxcairo.ImageSurfaceFromBitmap(self._stipple) self._pattern = cairo.SurfacePattern(img) self._pattern.set_extend(cairo.EXTEND_REPEAT) ctx.set_source(self._pattern) elif self._style == wx.USER_DASH: ctx.set_source_rgba(*_colourToValues(self._colour)) ctx.set_dash(self._dashes) elif self._style in [wx.DOT, wx.DOT_DASH, wx.LONG_DASH, wx.SHORT_DASH]: ctx.set_source_rgba(*_colourToValues(self._colour)) ctx.set_dash(_stdDashes(self._style, self._width)) elif self._style in [ wx.BDIAGONAL_HATCH, wx.CROSSDIAG_HATCH, wx.FDIAGONAL_HATCH, wx.CROSS_HATCH, wx.HORIZONTAL_HATCH, wx.VERTICAL_HATCH ]: pass # TODO make a stock pattern...
def setup_images(self): for img_name in ('audio-volume-high', 'audio-volume-low', 'audio-volume-medium', 'audio-volume-muted'): try: img = cairo.ImageSurface.create_from_png( os.path.join(self.theme_path, '%s.png' % img_name)) except cairo.Error, error: self.theme_path = None self.qtile.log.add(error) self.qtile.log.add('Volume switching to text mode') return input_width = img.get_width() input_height = img.get_height() sp = input_height / float(self.bar.height - 1) width = input_width / sp if width > self.width: self.width = int(width) + self.actual_padding * 2 imgpat = cairo.SurfacePattern(img) scaler = cairo.Matrix() scaler.scale(sp, sp) scaler.translate(self.actual_padding * -1, 0) imgpat.set_matrix(scaler) imgpat.set_filter(cairo.FILTER_BEST) self.surfaces[img_name] = imgpat
def draw(self, canvas, l, r): self.font.apply(canvas) _, _, w, h, _, _ = canvas.text_extents(self.text) if self.image: iw = self.image.get_width() ih = self.image.get_height() imh = self.height imw = int(iw / ih * imh + 0.5) scale = ih / imh if self.right: x = r - w - self.padding.right - imw else: x = l y = 0 pat = cairo.SurfacePattern(self.image) pat.set_matrix( cairo.Matrix(xx=scale, yy=scale, x0=-x * scale, y0=-y * scale)) pat.set_filter(cairo.FILTER_BEST) canvas.set_source(pat) canvas.rectangle(x, 0, imw, imh) canvas.fill() else: imw = 0 canvas.set_source(self.color) if self.right: x = r - self.padding.right - w r -= self.padding.left + self.padding.right + w + imw else: x = l + self.padding.left l += self.padding.left + self.padding.right + w + imw canvas.move_to(x, self.height - self.padding.bottom) canvas.show_text(self.text) return l, r
def __init__(self): # Initializing superclass super(Canvas, self).__init__() # Registering events self.add_events(gtk.gdk.BUTTON_PRESS_MASK | gtk.gdk.BUTTON_RELEASE_MASK | gtk.gdk.BUTTON1_MOTION_MASK | gtk.gdk.DRAG_MOTION | gtk.gdk.POINTER_MOTION_MASK) self.connect("button-press-event", self.button_pressed) self.connect("button-release-event", self.button_released) self.connect("motion-notify-event", self.move_event) self.connect("expose-event", self.expose) self.connect("motion-notify-event", self.motion_event) self.set_size(550, 412) self.image = cairo.ImageSurface.create_from_png("examples/flower.png") self.ALPHA_PATTERN = cairo.SurfacePattern( cairo.ImageSurface.create_from_png("pixmaps/alpha-pattern.png")) self.ALPHA_PATTERN.set_extend(cairo.EXTEND_REPEAT) # Basic tools self.DUMMY_TOOL = Tool(self) self.active_tool = self.DUMMY_TOOL # Final canvas self.CANVAS = cairo.ImageSurface(cairo.FORMAT_ARGB32, self.width, self.height)
def setup_images(self): for img_name in ('network-online', 'network-acquiring', 'network-offline'): try: img = cairo.ImageSurface.create_from_png( os.path.join(self.theme_path, '%s.png' % img_name)) except cairo.Error as error: self.theme_path = None self.width_type = bar.CALCULATED self.qtile.log.add(error) self.qtile.log.add('Switching to text mode') return input_width = img.get_width() input_height = img.get_height() sp = input_height/float(self.bar.height-1) width = input_width / sp if width > self.width: self.width = int(width) + self.actual_padding * 2 imgpat = cairo.SurfacePattern(img) scaler = cairo.Matrix() scaler.scale(sp, sp) scaler.translate(self.actual_padding*-1, 0) imgpat.set_matrix(scaler) imgpat.set_filter(cairo.FILTER_BEST) self.surfaces[img_name] = imgpat
def setup_images(self): for key, name in self.icons.iteritems(): try: path = os.path.join(self.theme_path, name) img = cairo.ImageSurface.create_from_png(path) except cairo.Error: self.theme_path = None self.qtile.log.warning('Battery Icon switching to text mode') return input_width = img.get_width() input_height = img.get_height() sp = input_height / float(self.bar.height - 1) width = input_width / sp if width > self.width: self.width = int(width) + self.actual_padding * 2 imgpat = cairo.SurfacePattern(img) scaler = cairo.Matrix() scaler.scale(sp, sp) scaler.translate(self.actual_padding * -1, 0) imgpat.set_matrix(scaler) imgpat.set_filter(cairo.FILTER_BEST) self.surfaces[key] = imgpat
def _configure(self, qtile, bar): base._Widget._configure(self, qtile, bar) if not self.filename: raise ValueError("Filename not set!") self.filename = os.path.expanduser(self.filename) try: self.image = cairo.ImageSurface.create_from_png(self.filename) except MemoryError: raise ValueError("The image '%s' doesn't seem to be a valid PNG" % (self.filename)) self.pattern = cairo.SurfacePattern(self.image) self.image_width = self.image.get_width() self.image_height = self.image.get_height() if self.scale: new_height = self.bar.height - (self.margin_y * 2) if new_height and self.image_height != new_height: scaler = cairo.Matrix() sp = self.image_height / float(new_height) self.image_height = new_height self.image_width = int(self.image_width / sp) scaler.scale(sp, sp) self.pattern.set_matrix(scaler)
def get_window_icon(self, window): cache = self._icons_cache.get(window.window.wid) if cache: return cache icons = sorted(window.icons.iteritems(), key=lambda x: abs(self.icon_size-int(x[0].split("x")[0]))) icon = icons[0] width, height = map(int, icon[0].split("x")) img = cairo.ImageSurface.create_for_data(icon[1], cairo.FORMAT_ARGB32, width, height) surface = cairo.SurfacePattern(img) scaler = cairo.Matrix() if height != self.icon_size: sp = height / float(self.icon_size) height = self.icon_size width = width / sp scaler.scale(sp, sp) surface.set_matrix(scaler) self._icons_cache[window.window.wid] = surface return surface
def render(self, widget, cr): # рендеринг widgetAllocation = self.get_allocation() # получаем разрешение виджета image = Image.new("RGB", (widgetAllocation.width, widgetAllocation.height)) # создаем изображение на # котором будем все склеивать tilex = self.lon2tilex(self.center[0], self.zoom) tiley = self.lat2tiley(self.center[1], self.zoom) startDrawingCoords = [ widgetAllocation.width / 2 - (tilex - int(tilex)) * self.tileSize[0], widgetAllocation.height / 2 - (tiley - int(tiley)) * self.tileSize[1] ] # получаем координаты первого(центрального) тайла для отрисовки в пикселях scope = self.delimitation(widgetAllocation, startDrawingCoords, self.tileSize) # определяем параметры экрана в широте и долготе self.screenLL[0] = self.tilex2lon( int(tilex) - int(scope[0]) + scope[0] % 1, self.zoom) # координаты self.screenLL[1] = self.tiley2lat( int(tiley) - int(scope[2]) + scope[2] % 1, self.zoom) self.screenLL[2] = self.tilex2lon( int(tilex) + int(scope[1]) + scope[1] % 1, self.zoom) - self.screenLL[0] # # ширина и высота self.screenLL[3] = -(self.tiley2lat( int(tiley) + int(scope[3]) + scope[3] % 1, self.zoom) - self.screenLL[1]) tempTilex = tilex - math.ceil(scope[0]) tempTiley = tiley - math.ceil(scope[2]) startDrawingCoords = [ startDrawingCoords[0] - math.ceil(scope[0]) * self.tileSize[0], startDrawingCoords[1] - math.ceil(scope[2]) * self.tileSize[1] ] print(self.screenLL) for i in range(math.ceil(scope[0]) + math.ceil(scope[2]) + 1): for j in range(math.ceil(scope[1]) + math.ceil(scope[3])): path = self.tile2path(tempTilex + j, tempTiley + i, self.zoom) print(path) response = requests.get(path, stream=True) tile = Image.open(response.raw) image.paste( tile, (int(startDrawingCoords[0] + j * self.tileSize[0]), int(startDrawingCoords[1] + i * self.tileSize[1]))) image.putalpha(255) arr = numpy.array(image) surface = cairo.ImageSurface.create_for_data(arr, cairo.FORMAT_RGB24, widgetAllocation.width, widgetAllocation.height) pt = cairo.SurfacePattern(surface) pt.set_extend(cairo.EXTEND_REPEAT) cr.set_source(pt) cr.rectangle(0, 0, widgetAllocation.width, widgetAllocation.height) cr.fill() self.drawCallBack(self, widget, cr, self.screenLL)
def pat(self, cr): sr1 = cairo.ImageSurface.create_from_png("pat-ex.png") pt1 = cairo.SurfacePattern(sr1) pt1.set_extend(cairo.EXTEND_REPEAT) cr.set_source(pt1) cr.rectangle(50,70,200,200) cr.fill()