def load_texture(key, path, region=None, mipmap=False, wrap=None): texture_path = join(RESOURCES_DIR, path) texture = Image(texture_path, mipmap=mipmap).texture if region: texture = texture.get_region(*region) textures[key] = texture
def getTexture(self,name, size): filename = join('art', name+'.png') texture = Image(filename).texture texture.wrap = 'repeat' texture.uvsize = size self.logger.info(filename) return texture
def __init__(self, *args, **kw): super(RootWidget, self).__init__(*args, **kw) texture = Image('wood.png').texture texture.wrap = 'repeat' texture.uvsize = (8, 8) with self.canvas: Rectangle(size=(2048, 2048), texture=texture)
class Image(object): EMPTY_IMAGE = Kivy_Image(Texture.create(size=(0, 0))) width = 0 height = 0 filename = None is_sequence_image = False def __init__(self, image = None, sequence = False, width = None, height = None, mipmap = True): if image is None: self.image = self.EMPTY_IMAGE self.width = 0 self.height = 0 return if isinstance(image, str): self.filename = image try: self.image = Kivy_Image(image, mipmap = mipmap) except: raise MyrmidonError("Couldn't load image from " + image) else: self.image = Kivy_Image(image) self.width = self.image.width self.height = self.image.height def destroy(self): """ Explicitly removes this image from the video memory and Kivy's cache. This functionality requires the custom kivy version at http://github.com/arcticshores/kivy """ if self.image is None or self.image is self.EMPTY_IMAGE: return from kivy.cache import Cache from kivy.graphics.opengl import glBindTexture, glDeleteTextures from kivy.logger import Logger Logger.debug("MyrmidonGFX: Destroying {0}".format(self.filename if self.filename else self.image)) # Remove from cache self.image.remove_from_cache() # Convert the ID to the right byte format for the GL method a1 = (self.image.texture.id >> 0) & 0xFF a2 = (self.image.texture.id >> 8) & 0xFF a3 = (self.image.texture.id >> 16) & 0xFF a4 = (self.image.texture.id >> 24) & 0xFF # Remove texture completely glBindTexture(self.image.texture.target, 0) glDeleteTextures(1, bytes(bytearray([a1, a2, a3, a4]))) # Since we've done a manual removal kivy shouldn't do it's own removal later self.image.texture.nofree = 1 # Stop this image from being used as a texture now self.image = None
def __init__(self, *args, **kwargs) : super(ScreenNexus, self).__init__(*args, **kwargs) texture = Image(os.path.join("res", "tile.png")).texture # Create background texture texture.wrap = "repeat" texture.uvsize = (12, 24) with self.canvas.before : # Draw background Color(1, 1, 1) Rectangle(texture = texture, size = (Window.width, Window.height), pos = self.pos)
def set_texture(self,path): #from kivy.core.image import Image tex = Image(path).texture tex.wrap = 'repeat' self.texture_sidebar = tex #tex = Image('style/1.png').texture if tex is not None: tex.wrap = 'repeat' self.texture = tex
def __init__(self, **kw): super(HelicopterGame, self).__init__(**kw) with self.canvas.before: texture = CoreImage('Images/background.png').texture texture.wrap = 'repeat' self.scroll_back = Rectangle(texture=texture, size=self.size, pos=self.pos) self.line=BezierLine() Clock.schedule_interval(self.update, 0)
def grass_background(widget): bg_texture = Image('resources/grass/grass-texture.png', nocache=True).texture # get POT texture #bg_texture = bg_texture.get_region(0, 0, 64, 64) #bg_texture.uvpos = (0, 0) bg_texture.uvsize = (35, 35) bg_texture.wrap = 'repeat' # fill all the background with widget.canvas.before: Rectangle(pos=(0, 0), size=(2560, 2560), texture=bg_texture)
def build(self): Window.bind(on_draw=self.ondraw) self.ui = MainUI() glb.root = self.ui glb.app = self self.texture_ruddertrim_wheel = CoreImage.load('img/ruddertrimwheel.png').texture self.texture_ruddertrim_wheel.wrap = 'repeat' self.texture_elevatortrim_wheel = CoreImage.load('img/elevatortrimwheel.png').texture self.texture_elevatortrim_wheel.wrap = 'repeat' return self.ui #show it
def capture(self, event): if (self.camera.play): self.camera.play = False img = Image(self.camera.texture) img.save("capture.png") self.captureButton.text="Take another" self.classifyButton.disabled=False else: self.camera.play = True self.captureButton.text="Capture" self.classifyButton.disabled = True
def print_png(self, filename, *args, **kwargs): '''Call the widget function to make a png of the widget. ''' fig = FigureCanvasAgg(self.figure) FigureCanvasAgg.draw(fig) l, b, w, h = self.figure.bbox.bounds texture = Texture.create(size=(w, h)) texture.blit_buffer(bytes(fig.get_renderer().buffer_rgba()), colorfmt='rgba', bufferfmt='ubyte') texture.flip_vertical() img = Image(texture) img.save(filename)
def _print_image(self, filename, *args, **kwargs): """Write out format png. The image is saved with the filename given. """ l, b, w, h = self.figure.bbox.bounds img = None if self.img_texture is None: texture = Texture.create(size=(w, h)) texture.blit_buffer(bytes(self.get_renderer().buffer_rgba()), colorfmt="rgba", bufferfmt="ubyte") texture.flip_vertical() img = Image(texture) else: img = Image(self.img_texture) img.save(filename)
def loadTileImages(self, ts): """ Loads the images in filename into Kivy Images. This is a port of the code here: https://github.com/bitcraft/PyTMX/blob/master/pytmx/tmxloader.py :type ts: pytmx.TiledTileset """ tile_image_path = self.map_dir + '/' + ts.source Logger.debug('KivyTiledMap: loading tile image at {}'.format(tile_image_path)) texture = CoreImage(tile_image_path).texture ts.width, ts.height = texture.size tilewidth = ts.tilewidth + ts.spacing tileheight = ts.tileheight + ts.spacing Logger.debug('KivyTiledMap: TiledTileSet: {}x{} with {}x{} tiles'.format(ts.width, ts.height, tilewidth, tileheight)) # some tileset images may be slightly larger than the tile area # ie: may include a banner, copyright, ect. this compensates for that width = int((((ts.width - ts.margin * 2 + ts.spacing) / tilewidth) * tilewidth) - ts.spacing) height = int((((ts.height - ts.margin * 2 + ts.spacing) / tileheight) * tileheight) - ts.spacing) Logger.debug('KivyTiledMap: TiledTileSet: true size: {}x{}'.format(width, height)) # initialize the image array Logger.debug('KivyTiledMap: initializing image array') self.images = [0] * self.maxgid p = itertools.product( xrange(ts.margin, height + ts.margin, tileheight), xrange(ts.margin, width + ts.margin, tilewidth) ) # trim off any pixels on the right side that isn't a tile # this happens if extra graphics are included on the left, but they are not actually part of the tileset width -= (ts.width - ts.margin) % tilewidth for real_gid, (y, x) in enumerate(p, ts.firstgid): if x + ts.tilewidth - ts.spacing > width: continue gids = self.map_gid(real_gid) if gids: # invert y for OpenGL coordinates y = ts.height - y - ts.tileheight tile = texture.get_region(x, y, ts.tilewidth, ts.tileheight) for gid, flags in gids: self.images[gid] = tile
def __init__(self, **kwargs): super(CanvasWidget, self).__init__(**kwargs) self.size = (512, 512) self._keyboard = Window.request_keyboard(self._keyboard_closed, self) self._keyboard.bind(on_key_down=self._on_keyboard_down) self.img = Image.open('test.png') self.img = self.img = self.img.transpose(Image.FLIP_TOP_BOTTOM) self.texture = Texture.create(size=(512,512)) self.texture.mag_filter = 'nearest' size = 512*512*3 buf = [] for r,g,b,a in self.img.getdata(): buf.extend([r,g,b,a]) #buf = [int(x*255/size) for x in range(size)] #buf = self._flatten_list(self.pixels) self.arr = array('B', buf) self.texture.blit_buffer(self.arr, colorfmt='rgba', bufferfmt='ubyte') with self.canvas: self.test = InstructionGroup() #self.test.add(Color(1, 1, 0, mode='rgb')) self.test.add(Rectangle(texture=self.texture, pos=self.pos, size=self.size, group='heh')) #self.bind(texture=self.on_texture_update) self.bind(pos=self.on_texture_update) self.bind(size=self.on_texture_update)
def init_game(self): is_start = False # bring stage self.bring_stage() self.character.velocity = [self.block_size / self.speed_ratio, 0] # map init with self.background_widget.canvas: texture = CoreImage('data/blue_land.png').texture texture.wrap = 'repeat' self.rect_1 = Rectangle( texture=texture, size=self.size, pos=self.pos) self.character_pos_init() self.init_stage()
def __init__(self, image = None, sequence = False, width = None, height = None, mipmap = True): if image is None: self.image = self.EMPTY_IMAGE self.width = 0 self.height = 0 return if isinstance(image, str): self.filename = image try: self.image = Kivy_Image(image, mipmap = mipmap) except: raise MyrmidonError("Couldn't load image from " + image) else: self.image = Kivy_Image(image) self.width = self.image.width self.height = self.image.height
def populate_palette(self): if self.tileset != None: # Set image self.tilesetImage = Image(self.tileset).texture # Set background image: backgroundImagePath = join(globals.subDirectory['graphics'], "emptytile.png") backgroundImage = Image(backgroundImagePath).texture # Find the resolution of this image: yDiv = (self.res[1] / self.res[0]) / 4 self.imageRes = [self.tilesetImage.width / 4 , self.tilesetImage.width * yDiv] # Set new dimensions self.width = self.res[0] * 4 + self.offset * 2 self.height = self.res[1] * (self.tilesetImage.height / (self.tilesetImage.width * yDiv)) + self.offset * 2 # Draw the background: with self.canvas.before: Color(1, 1, 1, 0.5) Rectangle(size = self.size, pos = (self.offset, self.offset)) for x in range(4): for y in range(int(self.tilesetImage.height / (self.tilesetImage.width * yDiv))): with self.canvas.before: Color(1, 1, 1, 0.1) Rectangle(texture = backgroundImage, size = self.res, pos = (x * self.res[0] + self.offset, y * self.res[1] + self.offset )) # Draw the tileset in the palette for x in range(4): for y in range(int(self.tilesetImage.height / (self.tilesetImage.width * yDiv))): with self.canvas: Color(1, 1, 1, 1) Rectangle(texture = self.tilesetImage.get_region(x * self.imageRes[0], y * self.imageRes[1], self.imageRes[0], self.imageRes[1]), size = self.res, pos = (x * self.res[0] + self.offset, y * self.res[1] + self.offset ))
def on_source(self, *args): v = self.source.split(".") source_down = ''.join(v[:-1])+"_down"+v[-1] self._fname_normal = resource_find(self.source) self._fname_down = resource_find(source_down) or self._fname_normal self.image_size = CoreImage.load(self._fname_normal).size self.background_normal = self._fname_normal self.background_down = self._fname_down
def populate_lists(self): for s in range(self.currentStory + 1): for l in range(len(self.renderList[s])): for i in range(self.iCount): for j in range(self.jCount): tile = self.mapFile.stories[self.currentStory].matrix[i][j] type = tile.get_graphics_type(l) if type[0] != None: graphicsInfo = tile.graphics[l] image = Image(graphicsInfo[0]).texture x = (i - j) * self.tileWidth / 2 + self.offset[0] + self.jCount * self.tileWidth / 2 y = (i + j) * self.tileHeight / 2 + self.offset[1] if (type[0] == 'object' or type[0] == 'wall') and type[1] == False: # Object means a rectangle, not animated means it goes into renderList self.renderList[s][l][i][j] = Rectangle(texture = image.get_region(graphicsInfo[1][0][0][0], graphicsInfo[1][0][0][1], graphicsInfo[2][0], graphicsInfo[2][1]), size = (self.tileWidth, self.tileWidth * graphicsInfo[2][1] / graphicsInfo[2][0]), pos = (x - self.tileWidth / 2, y) )
def render_tile(self, i, j, layer, story): tile = self.mapFile.stories[self.currentStory].matrix[i][j] type = self.mapFile.stories[story].matrix[i][j].get_graphics_type(layer) if type[0] != None: graphicsInfo = tile.graphics[layer] image = Image(graphicsInfo[0]).texture x = (i - j) * self.tileWidth / 2 + self.offset[0] + self.jCount * self.tileWidth/2 y = (i + j) * self.tileHeight / 2 + self.offset[1] self.renderList[story][layer][i][j].texture = image.get_region(graphicsInfo[1][0][0][0], graphicsInfo[1][0][0][1], graphicsInfo[2][0], graphicsInfo[2][1]) print("Type is:", type[0]) if type[0] == 'object' and type[1] == False: # Object means a rectangle, not animated means it goes into renderList self.renderList[story][layer][i][j].size = (self.tileWidth, self.tileWidth * graphicsInfo[2][1] / graphicsInfo[2][0]) self.renderList[story][layer][i][j].pos = (x - self.tileWidth/2, y) self.canvas.before.add(Color(1, 1, 1, 1)) for l in range(len(self.renderList[story])): if self.renderList[story][l][i][j] != [None]: self.canvas.before.add(self.renderList[story][l][i][j])
class Lamp(Widget): # Base variables TEXTURE = ObjectProperty(None) WIDTH = NumericProperty(1.0) HEIGHT = NumericProperty(1.0) X_UNIT = NumericProperty(1.0) Y_UNIT = NumericProperty(1.0) X = NumericProperty(1.0) Y = NumericProperty(1.0) # Run variables state = NumericProperty(1) xUnit = NumericProperty(1.0) yUnit = NumericProperty(1.0) curr_texture = ObjectProperty(None) x = NumericProperty(1.0) y = NumericProperty(1.0) def set_base(self, texture_dir, x, y): self.TEXTURE = Image(texture_dir).texture self.WIDTH = self.TEXTURE.width self.HEIGHT = self.TEXTURE.height self.X_UNIT = self.WIDTH / 3 self.Y_UNIT = self.HEIGHT / 1 self.X = x self.Y = y def reset(self): state = 1 def is_pressed(self, x, y): if x > self.x and y > self.y: if x < self.x + self.xUnit and y < self.y + self.yUnit: return True return False def change_state(self): self.state += 1 self.state %= 3 def update(self, xScale, yScale): self.xUnit = self.X_UNIT * xScale self.yUnit = self.Y_UNIT * yScale self.x = self.X * xScale self.y = self.Y * yScale self.curr_texture = self.TEXTURE.get_region(self.state * self.X_UNIT, 0, self.X_UNIT, self.Y_UNIT)
def start(win, ctx): # XXX use ctx ! global pointer_image, pointer_scale, pointer_alpha pointer_fn = ctx.config.get('image', join(kivy_data_dir, 'images', 'ring.png')) pointer_scale = float(ctx.config.get('scale', 1.0)) pointer_alpha = float(ctx.config.get('alpha', 1.0)) pointer_image = Image(pointer_fn) win.bind(on_touch_down=_touch_down, on_touch_move=_touch_move, on_touch_up=_touch_up)
def build(self): #wid = SpriteManager() root = BoxLayout(orientation='vertical') root.add_widget(self.wid) #Clock.schedule_interval(partial(self.add_rects, 1), 1) #self.add_rects(1) #self.addMovingRaindrop() #seems like a needed initialization step for future sprites to be added #Clock.schedule_interval(partial(self.addMovingRaindrop), 1.0/0.1) for img in os.listdir("./img"): if "atlas" in img: temp = img.split(".") Image(arg='atlas://img/' + temp[0] + '/frame0') elif "png" in img: Image(arg='img/' + img) Clock.schedule_interval(partial(self.wid.update), 1.0 / 60.0) return root
def set_base(self, texture_dir, x, y): self.TEXTURE = Image(texture_dir).texture self.WIDTH = self.TEXTURE.width self.HEIGHT = self.TEXTURE.height self.X_UNIT = self.WIDTH / 1 self.Y_UNIT = self.HEIGHT / 1 self.X = x self.Y = y
def do_layout(self, *args): self.add_widget(Image('Transparent.png')) number_of_children = len(self.children) width = self.width width_per_child = width / number_of_children positions = range(0, width, width_per_child) for position, child in zip(positions, self.children): child.height = self.height child.x = self.x + position child.y = self.y child.width = width_per_child
def __init__(self, pos): super(ButtonDisplay, self).__init__() self.border_color = Color(1, 1, 1) self.pos = pos self.add(self.border_color) self.border = Rectangle(texture=Image("pictures/black.png").texture, pos=pos, size=(Window.width / 2, 20)) self.add(self.border) self.time = 0 self.darkened = True
def test_detect_qrcode_frame_one_qrcode(self): """ Checks `_detect_qrcode_frame()` can detect one qrcode. """ fixture_path = os.path.join(FIXTURE_DIR, 'one_qr_code.png') texture = Image(fixture_path).texture code_types = self.zbarcam.code_types symbols = self.zbarcam._detect_qrcode_frame(texture, code_types) assert symbols == [ ZBarCam.Symbol(type='QRCODE', data=b'zbarlight test qr code') ]
def start(win, ctx): # XXX use ctx ! global pointer_image, pointer_scale, pointer_alpha pointer_fn = ctx.config.get('image', 'atlas://data/images/defaulttheme/ring') pointer_scale = float(ctx.config.get('scale', 1.0)) pointer_alpha = float(ctx.config.get('alpha', 1.0)) pointer_image = Image(pointer_fn) win.bind(on_touch_down=_touch_down, on_touch_move=_touch_move, on_touch_up=_touch_up)
def parse_image(filename): '''Parse a filename to load an image ro svg''' filename = parse_filename(filename) if filename in (None, 'None', u'None'): return None if filename.endswith('.svg'): return Svg(filename) else: return Image(filename) raise Exception('Error trying to load image specified in css: %s' \ % filename)
def draw_keys(self): layout = self.available_layouts[self.layout] layout_rows = layout['rows'] layout_geometry = self.layout_geometry layout_mode = self.layout_mode # draw background background = resource_find(self.background_disabled if self.disabled else self.background) texture = Image(background, mipmap=True).texture self.background_key_layer.clear() with self.background_key_layer: Color(*self.background_color) BorderImage(texture=texture, size=self.size, border=self.background_border) # XXX separate drawing the keys and the fonts to avoid # XXX reloading the texture each time # first draw keys without the font key_normal = resource_find(self.key_background_disabled_normal if self.disabled else self.key_background_normal) texture = Image(key_normal, mipmap=True).texture with self.background_key_layer: for line_nb in range(1, layout_rows + 1): for pos, size in layout_geometry['LINE_%d' % line_nb]: BorderImage(texture=texture, pos=pos, size=size, border=self.key_border) # then draw the text for line_nb in range(1, layout_rows + 1): key_nb = 0 for pos, size in layout_geometry['LINE_%d' % line_nb]: # retrieve the relative text text = layout[layout_mode + '_' + str(line_nb)][key_nb][0] z = Label(text=text, font_size=self.font_size, pos=pos, size=size, font_name=self.font_name) self.add_widget(z) key_nb += 1
def __init__(self, sType, app, **kwargs): self.sType = sType.lower() self.name = None self.app = app self.sOverlay = self.app.sOverlay self.players = self.app.overlay if self.sType in ("a", "c", "n", "r", "s", "b", "g", "q", "o"): self.texture = Image("crop/icons/{0}.png".format( self.sType)).texture self.texture_size = self.texture.size self.name = self.app.L.STR_BLOCK_A super(Special, self).__init__(**kwargs)
def __init__(self, shape, color=(1.0, 1.0, 1.0), texture_path=""): super(Obj, self).__init__() self.shape = shape self.color = Color(color[0], color[1], color[2]) self.add(self.color) self.add(self.shape) # rectangles only self.texture_path = texture_path if isinstance(self.shape, Rectangle) and self.texture_path != "": self.shape.texture = Image(self.texture_path).texture
def test_detect_qrcode_frame_one_qrcode_one_ean(self): """ Checks `_detect_qrcode_frame()` can detect one qrcode and one ean. """ fixture_path = os.path.join(FIXTURE_DIR, 'one_qr_code_and_one_ean.png') texture = Image(fixture_path).texture code_types = self.zbarcam.code_types symbols = self.zbarcam._detect_qrcode_frame(texture, code_types) self.assertEqual(symbols, [ ZBarCam.Symbol(type='QRCODE', data=b'zbarlight test qr code'), ZBarCam.Symbol(type='UPCA', data=b'012345678905') ])
def simple_rect(i, j, color, canvas=canvas): global height color_name = "" if (color[0] > 0): color_name = fig_colors[color[0] - 1][0] return Rectangle(texture=Image(color_name + ".png").texture, size=(size_factor, size_factor), pos=(j * size_factor, height - (i + 1) * size_factor)) else: canvas.add(Color(0, 0, 0)) return Rectangle(size=(size_factor, size_factor), pos=(j * size_factor, height - (i + 1) * size_factor))
def parse_image(filename): '''Parse a filename and load it in a Widget (Image or Svg). Svg is used only if the file extension is '.svg', otherwise Image.''' filename = parse_filename(filename) if filename in (None, 'None', u'None'): return None if filename.lower().endswith('.svg'): return Svg(filename) else: return Image(filename) raise Exception('Error trying to load image specified in css: %s' \ % filename)
def simple_rect_for_n(i, j, color): if (color[0] > 0): color_name = fig_colors[color[0] - 1][0] return Rectangle(texture=Image(color_name + ".png").texture, size=(size_factor, size_factor), pos=(next_fig_l_pos[0] + j * size_factor, 150 - (i + 1) * size_factor)) else: canvas.add(Color(0, 0, 0)) return Rectangle(size=(size_factor, size_factor), pos=(j * size_factor, height - (i + 1) * size_factor))
def __init__(self, image=None, sequence=False, width=None, height=None, mipmap=True): if image is None: self.image = self.EMPTY_IMAGE self.width = 0 self.height = 0 return if isinstance(image, str): self.filename = image try: self.image = Kivy_Image(image, mipmap=mipmap) except: raise MyrmidonError("Couldn't load image from " + image) else: self.image = Kivy_Image(image) self.width = self.image.width self.height = self.image.height
def _draw_element(m, texture='', texture1=''): #bind the texture BEFORE the draw (Mesh) if texture1: # here, we are binding a custom texture at index 1 # this will be used as texture1 in shader. tex1 = Image(texture1).texture tex1.wrap = 'repeat' #enable of uv support >1 or <0 BindTexture(texture=tex1, index=1) #clear the texture if none else: BindTexture(source="", index=1) mesh = Mesh( vertices=m.vertices, indices=m.indices, fmt=m.vertex_format, mode='triangles', group='truc', ) if texture: try: texture = Image(texture).texture texture.wrap = 'repeat' #enable of uv support >1 or <0 mesh.texture = texture except: #no texture if not found or not supported pass
def __init__(self): super(HomeScreen, self).__init__() # Create Title Background title_img = Image('../images/title-screen.png').texture title_screen = Rectangle(pos=(0, 0), size=(Window.width, Window.height + 10), texture=title_img) self.canvas.add(title_screen) w = Window.width // 3 buttonSize = (w, w // 3) buttonAnchor = (3 * Window.width // 4 - buttonSize[0] // 2, Window.height // 4 - buttonSize[1] // 2) # Create start button start_text = 'Start Game' startButton = create_button(start_text, buttonSize, buttonAnchor)[0] startButton.bind(on_release=self.switch_to_game_screen) self.add_widget(startButton) # Create stats button stats_text = 'Statistics' statsButton = create_button( stats_text, buttonSize, (buttonAnchor[0], buttonAnchor[1] - buttonSize[1]))[0] statsButton.bind(on_release=self.switch_to_score_card) self.add_widget(statsButton) # Load patterns information and create dropdown self.patterns_dict = loadPatterns() self.pattern = None # Create dropdown for patterns ddp_anchor = (Window.width // 4 - buttonSize[0] // 2, buttonAnchor[1]) self.mb_p, self.dd_p = create_dropdown( ['Select Pattern'] + list(self.patterns_dict), *buttonSize, ddp_anchor) self.add_widget(self.mb_p) self.dd_p.bind(on_select=self.set_pattern) # Load keys information and create dropdown self._generate_keys() self.key = None # Create dropdown for keys ddk_anchor = (ddp_anchor[0], ddp_anchor[1] - buttonSize[1]) self.mb_k, self.dd_k = create_dropdown( ['Select Key'] + list(self.keys_dict), *buttonSize, ddk_anchor) self.add_widget(self.mb_k) self.dd_k.bind(on_select=self.set_key) print('homescreen buttons initialized')
def __init__(self, **kwargs): self.ratio = Metrics.dpi / 100 self.texture_hard = Image('atlas://' + kivymd.images_path + 'el_shadows.atlas/h_shadow', mipmap=True).texture self.texture_soft = Image('atlas://' + kivymd.images_path + 'el_shadows.atlas/s_shadow', mipmap=True).texture super(ElevationBehaviour, self).__init__(**kwargs) with self.canvas.before: self._soft_col = Color(rgba=(1, 1, 1, .4)) self.border_soft = BorderImage(texture=self.texture_soft) self._hard_col = Color(rgba=(1, 1, 1, .16)) self.border_hard = BorderImage(texture=self.texture_hard) self.bind(pos=self.update_shadow, size=self.update_shadow, elevation=self.update_shadow) Clock.schedule_once(self.update_shadow, 0)
def test_detect_qrcode_frame_two_qrcodes(self): """ Checks `_detect_qrcode_frame()` can detect two qrcodes. """ fixture_path = os.path.join(FIXTURE_DIR, 'two_qr_codes.png') texture = Image(fixture_path).texture code_types = self.zbarcam.code_types symbols = self.zbarcam._detect_qrcode_frame(texture, code_types) Symbol = ZBarCam.Symbol self.assertEqual(symbols, [ Symbol(type='QRCODE', data=b'second zbarlight test qr code'), Symbol(type='QRCODE', data=b'zbarlight test qr code'), ])
def __init__(self, norm, pos, callback): super(GravitySelect, self).__init__() self.norm = norm self.callback = callback self.pos = pos self.margin = self.norm.nv(20) self.check_size = self.norm.nt((50, 50)) self.size = ( self.norm.nv(210), 2*self.margin + self.check_size[1] ) self.border_color = Color(50/255, 147/255, 140/255) # bluegreen self.border = Line(rectangle=(*self.pos, *self.size), width=2) self.add(self.border_color) self.add(self.border) self.check_color = Color(1, 1, 1) self.off = Rectangle( pos=(self.pos[0] + self.margin, self.pos[1] + self.margin), size=self.check_size, texture=Image('ui/buttons/unchecked.png').texture ) self.on = Rectangle( pos=(self.pos[0] + self.margin, self.pos[1] + self.margin), size=self.check_size, texture=Image('ui/buttons/checked.png').texture ) self.add(self.check_color) self.add(self.off) title_pos = ( self.pos[0] + self.norm.nv(140), self.pos[1] + self.check_size[1]/2 + self.margin ) self.title = CLabelRect(cpos=title_pos, text='gravity', font_size='18') self.add(Color(1, 1, 1)) self.add(self.title)
def set_base(self, game): self.game = game # Get resources self.imageManager = ImageManager() # Set background self.TEXTURE = Image(self.imageManager.roomdir).texture self.WIDTH = self.TEXTURE.width self.HEIGHT = self.TEXTURE.height self.X = 0.0 self.Y = 0.0 # Instantiate children self.navi.set_base(self.imageManager.navigatordir, 700.0, 525.0) self.back.set_base(self.imageManager.backdir, 350.0, 0.0) self.leftDoor.set_base(self.imageManager.leftdoordir, 45.0, 25.0) self.centerDoor.set_base(self.imageManager.centerdoordir, 325.0, 102.0) self.rightDoor.set_base(self.imageManager.rightdoordir, 640.0, 27.0) self.leftLamp.set_base(self.imageManager.leftlampdir, 80.0, 437.5) self.centerLamp.set_base(self.imageManager.centerlampdir, 375.0, 410.0) self.rightLamp.set_base(self.imageManager.rightlampdir, 668.0, 437.5) self.plant.set_base(self.imageManager.plantdir, 368.0, 268.0) self.bomb = Bomb() self.bomb.set_base(self.imageManager.bombdir, 368.0, 268.0) # Is there a door (at) [ahead, right, back, left] # Code: -1: no door; 0: door with green light; 1: door with grey light; 2: door with red light # and [number of bombs nearby, plant direction] # Code: -1: data not available; 0..n: number of bombs or direction of arrow self.roomProperty = [-1, -1, -1, -1, -1, -1] self.remove_widget(self.nBomb) self.remove_widget(self.gameTime) self.remove_widget(self.navi) self.remove_widget(self.back) self.remove_widget(self.leftDoor) self.remove_widget(self.centerDoor) self.remove_widget(self.rightDoor) self.remove_widget(self.leftLamp) self.remove_widget(self.centerLamp) self.remove_widget(self.rightLamp) self.remove_widget(self.plant) self.remove_widget(self.pause)
def take_not_window_screenshot(self, shouldWholeWindowIfNone=False, *args): if globals.baseSysConfig.get("background_image", "see_through"): img = ImageGrab.grab() try: im = CoreImage(self.ids["ParentScreenImage"].texture) except Exception: Logger.warning( globals.baseSysConfig.get("main", "parent_name") + ": Window background image does not have a texture") if shouldWholeWindowIfNone: self.minimize_screenshot() return data = BytesIO() im.save(data, fmt="png") data.seek(0) im = PILImage.open(data) wx, wy, ww, wh = CoreWindow.left, CoreWindow.top, CoreWindow.width, CoreWindow.height remAmount = globals.baseSysConfig.get("background_image", "crop_distance") remAmountTop = globals.baseSysConfig.get("background_image", "crop_distance_top") x, y, x2, y2 = wx - remAmount, wy - remAmountTop, wx + ww + remAmount, wy + wh + remAmount im = im.crop((x, y, x2, y2)) img.paste(im, (x, y)) data = BytesIO() img.save(data, format="png") data.seek(0) img = CoreImage(BytesIO(data.read()), ext='png') self.ids["ParentScreenImage"].texture = img.texture
def do_load(self): """Load the image.""" # This is the method that's actually called to load the asset from # disk. It's called by the loader thread so it's ok to block. However # since it's a separate thread, don't update any other attributes. # When you're done loading and return, the asset will be processed and # the various load status attributes will be updated automatically, # and anything that was waiting for it to load will be called. So # all you have to do here is load and return. if self.config.get('image_template'): try: template = self.machine.machine_config['image_templates'][self.config['image_template']] self.config = Util.dict_merge(template, self.config) except KeyError: raise KeyError("Image template '{}' was not found, referenced in image config {}".format( self.config['image_template'], self.config)) if self.machine.machine_config['mpf-mc']['zip_lazy_loading']: # lazy loading for zip file image sequences ImageLoader.zip_loader = KivyImageLoaderPatch.lazy_zip_loader self._image = Image(self.config['file'], keep_data=False, scale=1.0, mipmap=False, anim_delay=-1, nocache=True) self._image.anim_reset(False) if self.config.get('frame_skips'): # Frames are provided in 1-index values, but the image animates in zero-index values self.frame_skips = {s['from'] - 1: s['to'] - 1 for s in self.config['frame_skips']} # load first texture to speed up first display self._callbacks.add(lambda x: self._image.texture)
def refresh_active_keys_layer(self): self.active_keys_layer.clear() active_keys = self.active_keys layout_geometry = self.layout_geometry background = resource_find(self.key_background_down) texture = Image(background, mipmap=True).texture with self.active_keys_layer: Color(*self.key_background_color) for line_nb, index in active_keys.values(): pos, size = layout_geometry['LINE_%d' % line_nb][index] BorderImage(texture=texture, pos=pos, size=size, border=self.key_border)
def do_load(self): """Load the image.""" # This is the method that's actually called to load the asset from # disk. It's called by the loader thread so it's ok to block. However # since it's a separate thread, don't update any other attributes. # When you're done loading and return, the asset will be processed and # the various load status attributes will be updated automatically, # and anything that was waiting for it to load will be called. So # all you have to do here is load and return. if self.machine.machine_config['mpf-mc']['zip_lazy_loading']: # lazy loading for zip file image sequences ImageLoader.zip_loader = KivyImageLoaderPatch.lazy_zip_loader self._image = Image(self.config['file'], keep_data=False, scale=1.0, mipmap=False, anim_delay=-1, nocache=True) self._image.anim_reset(False)
def on_kill(self, is_pass=False): #self.size_anim = KFAnim((0,2*self.r),(.8,5*self.r)) self.is_pass = is_pass self.explosion_anim = Rectangle( pos=(self.image_texture.pos[0], self.image_texture.pos[1]), size=(self.image_texture.size[0], self.image_texture.size[1]), texture=Image("assets/explosion01.png").texture) self.add(self.explosion_anim) self.size_anim = KFAnim( (0, self.image_texture.size[0], self.image_texture.size[1]), (0.9, self.image_texture.size[0], self.image_texture.size[1])) self.color_anim = KFAnim((0, 0.8), (.3, 1), (0.8, 0)) self.time = 0 self.is_dead = True
def _mouse_move(win, pos, *args): global cursor_size if hasattr(win, '_cursor'): c = win._cursor else: with win.canvas.after: img = Image(cursor_image) Color(1, 1, 1, 1, mode='rgba') size = (cursor_size[0] or img.texture.size[0], cursor_size[1] or img.texture.size[1]) print(size) win._cursor = c = Rectangle(texture=img.texture, size=size) c.pos = pos[0] + cursor_offset[0], pos[1] - c.size[1] + cursor_offset[1]
def load_sprite(folder_path: Path, sp: str) -> Optional[SpriteConfig]: if sp.rsplit('.', 1)[-1] != 'png': return # It is probably a config file, not loading it config_file = (folder_path / sp.rsplit('.', 1)[0]).as_posix() + '_config.toml' sp_path = folder_path / sp if not os.path.exists(config_file): Logger.error( f"Engine: No configuration file found for {sp}, not loading it.") return texture = CoreImage(sp_path.as_posix()).texture texture.mag_filter = 'nearest' with open(config_file) as f: config_dict = toml.load(f) config = SpriteConfig(sp_path, texture, config_dict['size'], len(config_dict['animation']), [an['length'] for an in config_dict['animation']]) return config
def _parse_config(self, config): self._config = parse_xml(config) texture_path = self._parse_data('texture', 'name') config_dir_path = os.path.dirname(os.path.abspath(config)) path = os.path.join(config_dir_path, texture_path) if os.path.exists(path): self.texture_path = path else: self.texture_path = texture_path self.texture = Image(self.texture_path).texture self.emitter_x = float(self._parse_data('sourcePosition', 'x')) self.emitter_y = float(self._parse_data('sourcePosition', 'y')) self.emitter_x_variance = float(self._parse_data('sourcePositionVariance', 'x')) self.emitter_y_variance = float(self._parse_data('sourcePositionVariance', 'y')) self.gravity_x = float(self._parse_data('gravity', 'x')) self.gravity_y = float(self._parse_data('gravity', 'y')) self.emitter_type = int(self._parse_data('emitterType')) self.max_num_particles = int(float(self._parse_data('maxParticles'))) self.life_span = max(0.01, float(self._parse_data('particleLifeSpan'))) self.life_span_variance = float(self._parse_data('particleLifespanVariance')) self.start_size = float(self._parse_data('startParticleSize')) self.start_size_variance = float(self._parse_data('startParticleSizeVariance')) self.end_size = float(self._parse_data('finishParticleSize')) self.end_size_variance = float(self._parse_data('FinishParticleSizeVariance')) self.emit_angle = math.radians(float(self._parse_data('angle'))) self.emit_angle_variance = math.radians(float(self._parse_data('angleVariance'))) self.start_rotation = math.radians(float(self._parse_data('rotationStart'))) self.start_rotation_variance = math.radians(float(self._parse_data('rotationStartVariance'))) self.end_rotation = math.radians(float(self._parse_data('rotationEnd'))) self.end_rotation_variance = math.radians(float(self._parse_data('rotationEndVariance'))) self.speed = float(self._parse_data('speed')) self.speed_variance = float(self._parse_data('speedVariance')) self.radial_acceleration = float(self._parse_data('radialAcceleration')) self.radial_acceleration_variance = float(self._parse_data('radialAccelVariance')) self.tangential_acceleration = float(self._parse_data('tangentialAcceleration')) self.tangential_acceleration_variance = float(self._parse_data('tangentialAccelVariance')) self.max_radius = float(self._parse_data('maxRadius')) self.max_radius_variance = float(self._parse_data('maxRadiusVariance')) self.min_radius = float(self._parse_data('minRadius')) self.rotate_per_second = math.radians(float(self._parse_data('rotatePerSecond'))) self.rotate_per_second_variance = math.radians(float(self._parse_data('rotatePerSecondVariance'))) self.start_color = self._parse_color('startColor') self.start_color_variance = self._parse_color('startColorVariance') self.end_color = self._parse_color('finishColor') self.end_color_variance = self._parse_color('finishColorVariance') self.blend_factor_source = self._parse_blend('blendFuncSource') self.blend_factor_dest = self._parse_blend('blendFuncDestination')
class PixelPerfectCollisionBehavior(object): collision_source = StringProperty(None, allownone=True) '''The collision source is the file to load the collision mask from. The collision mask should be a png or other image file that supports the alpha layer. Any transparent pixels will count as no collision. Any opaque pixels will trigger a collision. The mask is scaled to fit the widget. ''' __collision_mask = ObjectProperty(None, allownone=True) '''The collision mask is used to detect the collision point against. If the collision mask is None then no collision will be possible. ''' def __init__(self, **kwargs): super(PixelPerfectCollisionBehavior, self).__init__(**kwargs) def on_collision_source(self, instance, value): if value is None: return try: self.__collision_mask = CoreImage(value, keep_data=True) except: self.__collision_mask = None def collide_point(self, x, y): if self.__collision_mask is None: # print("No collision mask") return False if not super().collide_point(x, y): # print("Not inside the widget") return False try: # print(x, y) # print(self.x, self.y, self.right, self.top) wscale = (self.__collision_mask.width / self.width) hscale = (self.__collision_mask.height / self.height) # print(wscale, hscale) # print(x, self.x) # print(y, self.y) # print((x - self.x) * wscale, (self.height - (y - self.y)) * hscale) # print(self.__collision_mask.width, self.__collision_mask.height) color = self.__collision_mask.read_pixel( (x - self.x) * wscale, (self.height - (y - self.y)) * hscale) # print(color) except Exception as e: color = 0, 0, 0, 0 if color[-1] > 0: print(self.x, self.y, 'collide') return True
def test_save_into_bytesio(self): Image = self.cls if setupconfig.PLATFORM == "darwin": # XXX on OSX CI Builder, img_sdl2 is not used # therefore the test below wont work yet with imageio only. return # load kivy logo img = Image.load("data/logo/kivy-icon-512.png") self.assertIsNotNone(img) # try to save without any format with self.assertRaises(Exception) as context: bio = io.BytesIO() img.save(bio) # save it in png bio = io.BytesIO() # if False, then there is no provider self.assertTrue(img.save(bio, fmt="png")) pngdata = bio.read() self.assertTrue(len(pngdata) > 0) # try to save in a filename try: _, filename = tempfile.mkstemp(suffix=".png") self.assertTrue(img.save(filename, fmt="png")) finally: os.unlink(filename) # XXX Test wrote but temporary commented # XXX because of the issue #6123 on OSX # XXX https://github.com/kivy/kivy/issues/6123 # with open(filename, "rb") as fd2: # pngdatafile = fd2.read() # # check the png file data is the same as bytesio # self.assertTrue(pngdata == pngdatafile) # save it in jpeg bio = io.BytesIO() # if False, then there is no provider self.assertTrue(img.save(bio, fmt="jpg")) self.assertTrue(len(bio.read()) > 0) with tempfile.NamedTemporaryFile(suffix=".jpg") as fd: self.assertTrue(img.save(fd.name))
class Navigator(Widget): # Base variables TEXTURE = ObjectProperty(None) WIDTH = NumericProperty(1.0) HEIGHT = NumericProperty(1.0) X_UNIT = NumericProperty(1.0) Y_UNIT = NumericProperty(1.0) X = NumericProperty(1.0) Y = NumericProperty(1.0) # Run variables angle = NumericProperty(0.0) xUnit = NumericProperty(1.0) yUnit = NumericProperty(1.0) curr_texture = ObjectProperty(None) x = NumericProperty(1.0) y = NumericProperty(1.0) def set_base(self, texture_dir, x, y): self.TEXTURE = Image(texture_dir).texture self.WIDTH = self.TEXTURE.width self.HEIGHT = self.TEXTURE.height self.X_UNIT = self.WIDTH / 1 self.Y_UNIT = self.HEIGHT / 1 self.X = x self.Y = y def update(self, xScale, yScale): self.xUnit = self.X_UNIT * xScale self.yUnit = self.Y_UNIT * yScale self.x = self.X * xScale self.y = self.Y * yScale self.curr_texture = self.TEXTURE.get_region(0, 0, self.X_UNIT, self.Y_UNIT)
def on_paths(self, *args): """Make textures from the images in ``paths``, and assign them at the same index in my ``texs`` as in my ``paths``. """ for i, path in enumerate(self.paths): if path in self.pathtexs: if ( self.pathtexs[path] in self.texs and self.texs.index(self.pathtexs[path])== i ): continue else: self.pathimgs[path] = img = Image.load( resource_find(path), keep_data=True ) self.pathtexs[path] = img.texture if i == len(self.texs): self.texs.append(self.pathtexs[path]) else: self.texs[i] = self.pathtexs[path]
def load_tileable(self, name): t = Image('%s.png' % name).texture t.wrap = 'repeat' setattr(self, 'tx_%s' % name, t)
def loadBackground(self): print 'loading bg', self.bg tex = CImage.load(self.bg, keep_data=True).texture self.buildBackground(tex)
def on_source(self, *largs): if os.path.exists(self.source): self.texture = Image.load(self.source).texture self.texture.wrap = 'repeat' self._calc_tex_coords()
from kivy.app import App from kivy.uix.widget import Widget from kivy.uix.image import Image from kivy.core.image import Image as ImageForTest from kivy.properties import NumericProperty, ReferenceListProperty, ObjectProperty from kivy.vector import Vector from kivy.factory import Factory from kivy.clock import Clock from kivy.core.window import Window from kivy.lang import Builder from kivy.graphics import Color import math m = ImageForTest.load('testme.png',keep_data=True) Builder.load_string(""" <PongBall>: size: 50, 50 """) class Mazy(Image): def on_touch_down(self,touch): print "Testing...",touch.x,touch.y print m.read_pixel(touch.x,touch.y) class PongBall(Image): r = NumericProperty(.5) g = NumericProperty(.5) b = NumericProperty(.5)
def load_tileable(self, name): t = Image('images/{}.png'.format(name)).texture t.wrap = 'repeat' setattr(self, 'tx_{}'.format(name), t)