def draw(self): x = y = 0 radius = 5 for page, view in self.pages.items(): w, h = [i for i in ui.measure_string(page, 0, self.tabfont)] dw, dh = [i + self.tabpad * 2 for i in (w, h)] if not isinstance(view, list): view.y += y + dh path1 = ui.Path.rounded_rect(x, y, dw, dh, radius) path2 = ui.Path.rect(x, y + dh - radius, dw, radius) view = [view, path1, path2] self.pages[page] = view view, path1, path2 = view if view == self.selpage: ui.set_color(0.89) else: ui.set_color(0.82) path1.fill() path2.fill() dy = y + dh/2. - h/2. ui.draw_string(page, (x, dy, dw, dh), self.tabfont, self.tabfg, ui.ALIGN_CENTER) x += dw
def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None): font = 'Menlo', prop.get_size_in_points() * 1.1 w, h = ui.measure_string(s, font=font, alignment=ui.ALIGN_RIGHT, line_break_mode=ui.LB_WORD_WRAP) y -= h if True or angle: with ui.GState(): ui.concat_ctm(ui.Transform.translation(x, y)) ui.concat_ctm( ui.Transform.rotation(-angle * matplotlib.numpy.pi / 180.)) ui.draw_string(s, rect=(0, 0, 0, 0), font=font, color='black', alignment=ui.ALIGN_RIGHT, line_break_mode=ui.LB_WORD_WRAP) else: ui.draw_string(s, rect=(x, y, 0, 0), font=font, color='black', alignment=ui.ALIGN_RIGHT, line_break_mode=ui.LB_WORD_WRAP)
def draw_text(self, text, x, y, font_name=None, font_size=None): if font_size is None: font_size = self.font_size if font_name is None: font_name = self.font_name if TXTDRW: wl, hl = ui.measure_string(text, 0, font=(font_name, font_size)) xo, yo = self.xyWorld(x, y) #.whUser(wl,hl) frm = (xo, yo - hl, wl, hl) #logger.debug('txtdrw:%s:%s fnt:%s,%s' % (text,(frm),font_name,font_size) ) ui.draw_string(text, frm, font=(font_name, font_size), color='black', alignment=ui.ALIGN_NATURAL, line_break_mode=ui.LB_WORD_WRAP) else: lbl = ui.Label() lbl.font = (font_name, font_size) lbl.text = text lbl.alignment = ui.ALIGN_LEFT lbl.size_to_fit() wl, hl = lbl.width, lbl.height lbl.x, lbl.y = self.xyWorld(x, y) lbl.y -= hl self.inView.add_subview(lbl)
def draw(self): r = ui.Rect(*self.bounds).inset(*self.circle_inset) oval = ui.Path.oval(r.x, r.y, r.width, r.height) c = ui.parse_color(self.circle_color) nc = (c[0], c[1], c[2], self.circle_alpha) # color with alpha pattern = '9' * len(self.text) text_rect = ui.Rect(0, 0, r.width * .8, r.height * .6) text_rect.center(r.center()) fs = self.get_max_fontsize(text_rect, pattern, self.font_name, self.inset_rect) with ui.GState(): ui.set_color(nc) oval.fill() ui.draw_string(self.text, rect=text_rect, font=(self.font_name, fs), color=self.text_color, alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL) j = ui.Path.rect(*text_rect) ui.set_color((0, 0, 0, .5)) j.fill()
def __init__(self): self.dropped_sprites = set() # Initialize the floor collision body: w = self.size[0] self.physics_body = sk.PhysicsBody.edge_loop_rect(0, -100, w, 100) # Draw and cache textures for all numbers: self.textures = {} for n in '0123456789:': w, h = s * 2 + 10, s * 2 with ui.ImageContext(w, h) as ctx: ui.draw_string(n, font=('AvenirNext-Regular', h * 0.94), rect=(0, 0, w, h), color='white', alignment=ui.ALIGN_CENTER) img = ctx.get_image() self.textures[n] = sk.Texture(img) margin = (self.size[0] - 7 * s) / 2 self.clock_nodes = [] self.time_str = time.strftime('%H:%M:%S') # Create a sprite node for every character in the time string: for i, c in enumerate(self.time_str): sprite = sk.SpriteNode(self.textures[c]) sprite.position = i * s + margin, self.size[1] - 200 self.add_child(sprite) self.clock_nodes.append(sprite)
def draw_face(self, diameter, border, font_size): with ui.ImageContext(diameter, diameter) as ctx: ui.set_color('white') circle = ui.Path.oval(border / 2, border / 2, diameter - border, diameter - border) circle.line_width = border - 1 circle.fill() ui.set_color('silver') with ui.GState(): ui.set_shadow((0, 0, 0, 0.35), 0, 1, 5.0) circle.stroke() angle = (-pi / 2) + (pi * 2) / 12.0 for i in range(1, 13): number = str(i) x = diameter / 2 + cos(angle) * (diameter / 2 - font_size * 1.2) y = diameter / 2 + sin(angle) * (diameter / 2 - font_size * 1.2) font = ('HelveticaNeue-UltraLight', font_size) w, h = ui.measure_string(number, font=font) rect = (x - 50, y - h / 2, 100, h) ui.draw_string(number, rect=rect, font=font, alignment=ui.ALIGN_CENTER) angle += (pi * 2.0) / 12.0 return ctx.get_image()
def emoji_to_image(emoji_char, w=32, h=32, font_name='Arial Rounded MT Bold', font_size=28, file_path=None): r = ui.Rect(0, 0, w, h) with ui.ImageContext(r.width, r.height) as ctx: # just draw the string ui.draw_string(emoji_char, rect=r, font=(font_name, font_size), color='black', alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL) img = ctx.get_image() # write a file if file_path if file_path: with open(file_path, 'wb') as file: file.write(img.to_png()) return img
def draw(self): t = localtime() ui.draw_string("{:02}:{:02}:{:02}".format( t.tm_hour, t.tm_min, t.tm_sec), font=('Helvetica', 20), rect=(100, 100,0,0), alignment=ui.ALIGN_CENTER)
def draw_label(self): owner = self.owner ui.set_color('purple') s = str('{:.0%}'.format(owner.value)) lb_rect = ui.Rect(*owner.cv) lb_rect.center(owner.center) ui.draw_string(s, lb_rect , font=('Arial Rounded MT Bold', 22), color='black', alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL)
def draw(self): t0 = (self.value // (600 * 60), self.value // 600, self.value // 10) t1 = (t0[0], t0[1] % 60, t0[2] % 60) ui.draw_string("{:02}:{:02}:{:02}".format(*t1), font=('Helvetica', 20), rect=(150, 0, 0, 0), color='black', alignment=ui.ALIGN_CENTER)
def draw(self): # 検出した顔の輪郭に合わせて、表示を加工 #if faces is not None and faces.count() != 0: if faces is not None and len(faces) != 0: # # カメラの画像は X軸=1920 Y軸=1080 # # View は X軸=375 Y軸=667 # # 画像のX軸Y軸をViewのY軸X軸に対応させ、サイズを調整 label_status.text = '' person_counter = 0 for face in faces: label = face[0] confidence = round(face[1], 3) x = face[2] y = face[3] w = face[4] h = face[5] # CoreImageは座標系が左下0なので、左上0に変換する。 y = 1 - y - h # boundingBox座標は正規化されているので戻す x = x * image_width y = y * image_height w = w * image_width h = h * image_height # 画像のX軸Y軸をViewのY軸X軸に対応させ、サイズを調整 x2 = y * self.width / image_height y2 = x * self.height / image_width w2 = h * self.width / image_height h2 = w * self.height / image_width if label == 'person': COL = 'blue' person_counter = person_counter + 1 else: COL = 'red' #ui.set_color('red') ui.set_color(COL) # ui.fill_rect(x2, y2, w2, h2) bb = ui.Path.rect(x2, y2, w2, h2) bb.stroke() ui.draw_string(label, rect=(x2, y2, w2, h2), color=COL) #with ui.GState(): # ui.concat_ctm(ui.Transform.rotation(np.pi/2) ) # ui.draw_string(label, rect=(x2,y2,w2,h2) ) label_status.text = label_status.text + label + ':' + str( confidence) + ' ' if person_counter >= 3: label_status.text = "百合子「蜜です!」"
def update_texture(self): if self._suspend_updates: return w, h = ui.measure_string(self.text, font=self.font) with ui.ImageContext(max(w, 1), max(h, 1)) as ctx: ui.draw_string(self.text, (0, 0, w, h), self.font, color='white') img = ctx.get_image() self.texture = Texture(img) self._rendered_text = self.text
def draw(self): # redraw button def darken(color): return tuple([0.5 * x for x in color]) #set up button size to fit. padding = 10 textsize = ui.measure_string(string=self.title, max_width=0, font=self.font, alignment=ui.ALIGN_CENTER) #draw border ui.set_color(self.border_color) path = ui.Path.rounded_rect(0, 0, self.width, self.height, self.corner_radius) path.line_width = self.border_width path.stroke() #fill button, depending on touch state if self.touched: if self.doing_longtouch: ui.set_color('blue') else: ui.set_color('grey') else: ui.set_color(self.bg_color) path.fill() # fill corner darker, if has children if self.flow.subviews: corner = ui.Path() corner.move_to(self.width - 1.5 * self.corner_radius, 0) corner.line_to(self.width, 0) corner.line_to(self.width, 1.5 * self.corner_radius) corner.line_to(self.width - 1.5 * self.corner_radius, 0) ui.set_color(darken(darken(self.bg_color))) corner.stroke() corner.fill() # draw title, center vertically, horiz rect = list(self.bounds) rect[1] = (rect[3] - textsize[1]) / 2 #vert center rect[2] = max(rect[2], textsize[0] + 10) ui.draw_string(self.title, rect=tuple(rect), font=self.font, color=self.tint_color, alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_WORD_WRAP) if textsize[0] > self.bounds[2]: self.width = textsize[0] + 10
def draw(self): path_border = ui.Path.rect(self.my_border_x, self.my_border_y, self.my_border_width, self.my_border_height) ui.set_color('black') path_border.stroke() path_bar = ui.Path.rect(self.bar_x, self.bar_y, self.bar_width, self.bar_height) ui.set_color('blue') path_bar.fill() ui.draw_string(self.txt, rect=(self.my_border_x + self.my_border_width + 2, self.my_border_y + 3, 50, self.my_border_height), alignment=ui.ALIGN_CENTER)
def emoji_to_image(emoji_char, w=32, h=32, font_name='Arial Rounded MT Bold'): font_size = min(w, h) - 8 r = ui.Rect(0, 0, w, h) with ui.ImageContext(r.width, r.height) as ctx: # just draw the string ui.draw_string(emoji_char, rect=r, font=(font_name, font_size), color='black', alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL) img = ctx.get_image() return img
def main(): images = photos.pick_image(multi=True, original=upload_originals, raw_data=upload_originals) if images is None: return for i, img in enumerate(images): print('Uploading image %i/%i...' % (i + 1, len(images))) if not upload_originals: b = BytesIO() img.save(b, 'JPEG', quality=jpeg_quality) data = b.getvalue() else: data = img r = requests.post('http://how-old.net/Home/Analyze?isTest=False', files={'file': ('someimage.jpg', data)}) d = json.loads(json.loads(r.text)) faces = d.get('Faces') ui_img = ui.Image.from_data(data) scale = result_size / max(ui_img.size) w, h = ui_img.size[0] * scale, ui_img.size[1] * scale with ui.ImageContext(w, h) as ctx: ui_img.draw(0, 0, w, h) for face in faces: rect = [ float(face['faceRectangle'][key]) * scale for key in ['left', 'top', 'width', 'height'] ] caption_rect = (rect[0], rect[1], max(40, rect[2]), 16) ui.set_color((0, 0, 0, 0.5)) ui.Path.rect(*rect).stroke() ui.fill_rect(*caption_rect) attrs = face['attributes'] age = attrs['age'] if age % 1.0 == 0: age = int(age) caption = '%s (%s)' % (age, attrs['gender'][0]) ui.draw_string(caption, caption_rect, color='white') result_img = ctx.get_image() result_img.show() if faces: faces_str = ', '.join([ '%s (%s)' % (face['attributes']['age'], face['attributes']['gender']) for face in faces ]) print('%i face%s: %s' % (len(faces), 's' if len(faces) != 1 else '', faces_str)) else: print('No faces found') print('Done')
def draw(self): path = ui.Path.oval(50, 50, 400, 100) ui.set_color((1.0, 0.4, 0.4, 1.0)) path.fill() path.line_width = 10.0 ui.set_color((0.8, 1.0, 0.5, 1.0)) path.stroke() ui.draw_string('Label', rect=(50, 175, 400, 100), font=tuple(('Georgia', 20)), color=(0.4, 0.6, 1.0, 1.0), alignment=0, line_break_mode=4) ui.Image("Dog_Face").draw(50, 200, 300, 300)
def update_texture(self): if self._suspend_updates: return w, h = ui.measure_string(self.text, font=self.font) # Round up size to next multiple of screen scale # (makes it easier to get crisp rendering in common cases) s = get_screen_scale() w = math.ceil(w / s) * s h = math.ceil(h / s) * s with ui.ImageContext(max(w, 1), max(h, 1)) as ctx: ui.draw_string(self.text, (0, 0, w, h), self.font, color='white') img = ctx.get_image() self.texture = Texture(img) self._rendered_text = self.text
def create_image(): img = None x1, y1, w1, h1 = main_view['view1'].frame x2, y2, w2, h2 = main_view['imageview1'].frame x, y = x1 - x2, y1 - y2 im1 = main_view['imageview1'].image with ui.ImageContext(w2, h2) as ctx: im1.draw(0, 0, w2, h2) if input_info[0] == 'text': ui.draw_string(input_info[1], rect=(x, y, 0, 0)) elif input_info[0] == 'image': ui.Image(input_info[1]).draw(x, y, w1, h1) elif input_info[0] == 'shape': make_shape(input_info[1], x, y, w1, h1) img = ctx.get_image() return img
def draw(self): r = min(self.width, self.height) / 2 * 0.9 circle = ui.Path.oval(0, 0, r * 2, r * 2) circle.line_width = 6 shadow = ('black', 0, 0, 15) ui.set_shadow(*shadow) ui.set_color('silver') #self.face = ShapeNode(circle, 'white', 'silver', shadow=shadow) circle.fill() circle.stroke() for i in range(12): label = LabelNode(str(i + 1), font=('HelveticaNeue-UltraLight', 0.2 * r)) label.color = 'black' a = 2 * pi * (i + 1) / 12.0 #label.position = sin(a)*(r*0.85), cos(a)*(r*0.85) label.position = sin(a) * (r * 0.85), cos(a) * (r * 0.85) #print(label.position) ui.draw_string(str(i + 1), rect=(r + label.position[0], r + label.position[1], 0, 0), font=('<system>', 18), color='black', alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_WORD_WRAP) #self.hands = [] #hand_attrs = [(r*0.6, 8, 'black'), (r*0.9, 8, 'black'), (r*0.9, 4, 'red')] #self.hands = [(r*0.6, 8, 'black'), (r*0.9, 8, 'black'), (r*0.9, 4, 'red')] t = datetime.now() tick = -2 * pi / 60.0 seconds = t.second + t.microsecond / 1000000.0 minutes = t.minute + seconds / 60.0 hours = (t.hour % 12) + minutes / 60.0 self.hands[0] = 5 * tick * hours self.hands[1] = tick * minutes self.hands[2] = tick * seconds #print(type(self.hands)) for l, w, color in self.hands: #shape = ShapeNode(ui.Path.rounded_rect(0, 0, w, l, w/2), color) shape = ui.Path.rounded_rect(0, 0, w, l, w / 2) #shape.anchor_point = (0.5, 0) shape.stroke()
def draw(self): ui.set_color('#494949') # 绘制y轴 ui.fill_rect(self.y_axe_x,self.y_axe_y,self.y_axe_w,self.y_axe_h) for i in range(int((self.y_axe_h-25)/25)): price=str(i*25) price_x=self.y_axe_x-45 price_y=self.height-self.offsey_y-60-i*25 price_w=40 price_h=20 if(i==0): price="free" ui.draw_string(price,(price_x,price_y,price_w,price_h),('<system>',16),alignment=ui.ALIGN_RIGHT) ui.fill_rect(self.y_axe_x-5,price_y+(price_h-2)/2,5,2)
def draw(self): # redraw button def darken(color): return tuple([0.5*x for x in color]) #set up button size to fit. padding=10 textsize=ui.measure_string(string=self.title,max_width=0,font=self.font,alignment=ui.ALIGN_CENTER) #draw border ui.set_color(self.border_color) path = ui.Path.rounded_rect(0, 0, self.width, self.height,self.corner_radius) path.line_width=self.border_width path.stroke() #fill button, depending on touch state if self.touched: if self.doing_longtouch: ui.set_color('blue') else: ui.set_color('grey') else : ui.set_color(self.bg_color) path.fill() # fill corner darker, if has children if self.flow.subviews: corner = ui.Path() corner.move_to(self.width-1.5*self.corner_radius,0) corner.line_to(self.width,0) corner.line_to(self.width,1.5*self.corner_radius) corner.line_to(self.width-1.5*self.corner_radius,0) ui.set_color(darken(darken(self.bg_color))) corner.stroke() corner.fill() # draw title, center vertically, horiz rect=list(self.bounds) rect[1]=(rect[3]-textsize[1])/2 #vert center rect[2]=max(rect[2],textsize[0]+10) ui.draw_string(self.title, rect=tuple(rect), font=self.font, color=self.tint_color, alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_WORD_WRAP) if textsize[0]>self.bounds[2]: self.width=textsize[0]+10
def draw(self): ''' called by iOS whenever set_needs_display is called, or whenever os decides it is needed, for instance view rotates''' # set color to red ui.set_color((1, 0, 0)) # create a copy of self.pts, and append the current point drawpts = self.pts if drawpts: # move path to first point: pth = ui.Path() pth.move_to(*drawpts[0]) p0 = drawpts[0] for p in drawpts[1:]: # for each point after the first, draw a line from the previous point, compute length vector L # draw the line segment pth.line_to(*p) # compute point which is halfway along line between the # start/end point. L is the vector pointing from start to # finish. H is the Point at the halfway, referenced back to # global origin L = (ui.Point(*p) - ui.Point(*p0)) P0 = ui.Point(*p0) H = P0 + L / 2 # halfway point # put text at the halfway point, containing length ofmsegment * # scale ui.draw_string('%3.2f' % abs(L * self.scale.value / 10), (H.x, H.y, 0, 0), color='red') # set starting point for next line segment p0 = p pth.stroke() # draw the path if len(drawpts) > 2: # 'close' the path to show area computed with ui.GState(): pth = ui.Path() pth.move_to(*drawpts[-1]) pth.line_to(*drawpts[0]) pth.set_line_dash([2, 3]) ui.set_color((1, .5, .5, .5)) pth.stroke() # create a 10 pixel circle at last entered point ui.Path.oval(drawpts[-1][0] - 5, drawpts[-1][1] - 5, 10, 10).fill() # show circles for previously entered points. smaller and lighter ui.set_color((1, .5, .5)) for p in drawpts[0:-1]: ui.Path.oval(p[0] - 3, p[1] - 3, 6, 6).fill()
def create_image(): img = None with ui.ImageContext(500, 500) as ctx: path = ui.Path.oval(50, 50, 400, 100) ui.set_color((1.0, 0.4, 0.4, 1.0)) path.fill() path.line_width = 10.0 ui.set_color((0.8, 1.0, 0.5, 1.0)) path.stroke() ui.draw_string('Label', rect=(50, 175, 400, 100), font=tuple(('Georgia', 20)), color=(0.4, 0.6, 1.0, 1.0), alignment=0, line_break_mode=4) ui.Image("Dog_Face").draw(50, 200, 300, 300) img = ctx.get_image() return img
def draw(self): ''' called by iOS whenever set_needs_display is called, or whenever os decides it is needed, for instance view rotates''' # set color to red ui.set_color((1, 0, 0)) # create a copy of self.pts, and append the current point drawpts = self.pts if drawpts: # move path to first point: pth = ui.Path() pth.move_to(*drawpts[0]) p0 = drawpts[0] for p in drawpts[1:]: # for each point after the first, draw a line from the previous point, compute length vector L # draw the line segment pth.line_to(*p) # compute point which is halfway along line between the # start/end point. L is the vector pointing from start to # finish. H is the Point at the halfway, referenced back to # global origin L = (ui.Point(*p) - ui.Point(*p0)) P0 = ui.Point(*p0) H = P0 + L / 2 # halfway point # put text at the halfway point, containing length ofmsegment * # scale ui.draw_string('%3.2f' % abs( L * self.scale.value / 10), (H.x, H.y, 0, 0), color='red') # set starting point for next line segment p0 = p pth.stroke() # draw the path if len(drawpts) > 2: # 'close' the path to show area computed with ui.GState(): pth = ui.Path() pth.move_to(*drawpts[-1]) pth.line_to(*drawpts[0]) pth.set_line_dash([2, 3]) ui.set_color((1, .5, .5, .5)) pth.stroke() # create a 10 pixel circle at last entered point ui.Path.oval(drawpts[-1][0] - 5, drawpts[-1][1] - 5, 10, 10).fill() # show circles for previously entered points. smaller and lighter ui.set_color((1, .5, .5)) for p in drawpts[0:-1]: ui.Path.oval(p[0] - 3, p[1] - 3, 6, 6).fill()
def draw(self): ui.set_color((1,0,0)) drawpts=[p for p in self.pts] if self.currpt: drawpts+=[self.currpt] if drawpts: pth=ui.Path() pth.move_to(*drawpts[0]) p0=drawpts[0] for p in drawpts[1:]: if p: pth.line_to(*p) L=(ui.Point(*p)-ui.Point(*p0)) P0=ui.Point(*p0) p0=p H=P0+L/2 ui.draw_string('%3.2f'%abs(L*float(self.scale.text)),(H.x,H.y,0,0),color='red') pth.stroke() ui.Path.oval(drawpts[-1][0]-5,drawpts[-1][1]-5,10,10).fill()
def draw(self): square_size=min(self.width,self.height) N=self.N Nb=self.Nb dx=square_size*1.0/(N+2) dxb=N*dx/Nb h,s,v=self.current i0,j0,k0=(round(c*N) for c in self.current) k0=round(self.current[2]*Nb) #draw H/S grid for i in xrange(0,N): for j in xrange(0,N): ui.set_color(colorsys.hsv_to_rgb(i*1.0/N,j*1.0/N,v)) ui.set_blend_mode(ui.BLEND_NORMAL) ui.fill_rect(round(i*dx),round(j*dx),round(dx),round(dx)) #draw V slider for k in xrange(0,Nb): ui.set_color(colorsys.hsv_to_rgb(h,s,k*1./Nb)) ui.set_blend_mode(ui.BLEND_NORMAL) ui.fill_rect(round((N+1)*dx),round(k*dxb),round(dx),round(dxb+0.5)) #highlight selection if all([c>=0 for c in self.current]): ui.set_color(colorsys.hsv_to_rgb(h,s,1-0.5*(1-v))) p=ui.Path.rect(i0*dx,j0*dx,dx,dx) p.line_width=4 p.stroke() ui.set_color(colorsys.hsv_to_rgb(h,s,1-0.5*(1-v))) p=ui.Path.rect((N+1)*dx,k0*dxb,dx,dxb) p.line_width=4 p.stroke() #preview ui.set_color(colorsys.hsv_to_rgb(h,s,v)) ui.fill_rect(0,(N+1)*dx,6*dx,dx) r,g,b=colorsys.hsv_to_rgb(h,s,v) clip=lambda x:min(max(x,0),1) rp,gp,bp=colorsys.hsv_to_rgb(1-h,1,clip((0.5-v)*100)) ui.draw_string( ('{:02x}'*3).format(int(r*255),int(g*255),int(b*255)), (0,(N+1)*dx,6*dx,dx),alignment=ui.ALIGN_CENTER,color=(rp,gp,bp))
def __init__(self): with open('words_en.data') as f: self.words = marshal.load(f) self.root = sk.Node() self.did_change_size(None) self.add_child(self.root) self.background_color = '#0b1d28' textures = {} for letter in letter_freq: with ui.ImageContext(tile_size, tile_size) as ctx: shadow = ui.Path.rounded_rect(0, 0, tile_size, tile_size, 5) ui.set_color('silver') shadow.fill() bg = ui.Path.rounded_rect(0, 0, tile_size, tile_size - 4, 5) ui.set_color('white') bg.fill() font = ('AvenirNext-Regular', font_size) w, h = ui.measure_string(letter.upper(), font=font) x, y = (tile_size - w) / 2, (tile_size - h) / 2 ui.draw_string(letter.upper(), rect=(x, y, w, h), font=font, color='black') textures[letter] = sk.Texture(ctx.get_image()) self.tile_textures = textures self.tiles = [[None] * rows for i in xrange(cols)] for x, y in product(xrange(cols), xrange(rows)): letter = choice(letter_bag) s = sk.SpriteNode(self.tile_textures[letter]) s.user_info = {'letter': letter, 'x': x, 'y': y} pos_x = tile_size / 2 + x * (tile_size + padding) pos_y = tile_size / 2 + y * (tile_size + padding) if x % 2 != 0: pos_y += tile_size / 2 s.position = pos_x, pos_y s.color_blend_factor = 1 s.color = 'white' self.tiles[x][y] = s self.root.add_child(s) self.selected = [] self.touched_tile = None
def __init__(self): with open('words_en.data') as f: self.words = marshal.load(f) self.root = sk.Node() self.add_child(self.root) self.background_color = '#0b1d28' textures = {} for letter in letter_freq: with ui.ImageContext(tile_size, tile_size) as ctx: shadow = ui.Path.rounded_rect(2, 2, tile_size - 4, tile_size - 4, 5) ui.set_color('silver') shadow.fill() bg = ui.Path.rounded_rect(2, 2, tile_size - 4, tile_size - 8, 5) ui.set_color('white') bg.fill() font = ('AvenirNext-Regular', font_size) w, h = ui.measure_string(letter.upper(), font=font) x, y = (tile_size - w) / 2, (tile_size - h) / 2 ui.draw_string(letter.upper(), rect=(x, y, w, h), font=font, color='black') textures[letter] = sk.Texture(ctx.get_image()) self.tile_textures = textures self.tiles = [] #[[None]*rows for i in xrange(cols)] for x, y in product(xrange(cols), xrange(rows)): s = self.create_tile(x, y) self.tiles.append(s) self.root.add_child(s) self.selected = [] self.touched_tile = None self.score_label = sk.LabelNode() self.score_label.font_name = 'AvenirNext-Regular' self.score_label.font_size = 50 self.score_label.h_align = sk.H_ALIGN_CENTER self.score_label.text = '0' self.score = 0 self.add_child(self.score_label) self.did_change_size(None)
def draw_text(self, **kwargs): if kwargs: self.do_kwargs(**kwargs) r = ui.Rect(*self.rect).inset(*self.margin).translate(*self.origin) my_center = r.center() font_size = self.font_size if not font_size: result = self.get_max_fontsize() r1 = ui.Rect(*result[1]) font_size = result[0] else: w, h = ui.measure_string(self.text, max_width=0, font=(self.font_name, font_size), alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL) r1 = ui.Rect(0, 0, w, h) r1.center(my_center) with ui.GState(): if self.rotate: ''' help from @omz https://forum.omz-software.com/topic/3180/understanding-ui-transform-rotation ''' ui.concat_ctm(ui.Transform.translation(*r1.center())) ui.concat_ctm(ui.Transform.rotation(math.radians(self.rotate))) ui.concat_ctm(ui.Transform.translation(*r1.center() * -1)) if self.use_shadow: ui.set_shadow(*self.shadow_params) ui.draw_string(self.text, rect=r1, font=(self.font_name, font_size), color=self.text_color, alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL)
def draw(self): ui.set_color((1, 0, 0)) drawpts = [p for p in self.pts] if self.currpt: drawpts += [self.currpt] if drawpts: pth = ui.Path() pth.move_to(*drawpts[0]) p0 = drawpts[0] for p in drawpts[1:]: if p: pth.line_to(*p) L = (ui.Point(*p) - ui.Point(*p0)) P0 = ui.Point(*p0) p0 = p H = P0 + L / 2 ui.draw_string('%3.2f' % abs(L * float(self.scale.text)), (H.x, H.y, 0, 0), color='red') pth.stroke() ui.Path.oval(drawpts[-1][0] - 5, drawpts[-1][1] - 5, 10, 10).fill()
def draw(self): x = 0 for i in range(0, 5): r = ui.Rect(x, 0, self.height, self.height).inset(10, 10) s = ui.Path.oval(*r) ui.set_color(_colors[i]) s.fill() if not i: r1 = ui.Rect(r.x, r.y, r.width, 22) r1.center(r.center()) r1.x = r.x # only draw text on 0 item ui.draw_string(str(self.row), rect=r1, font=('Arial Rounded MT Bold', 22), color='white', alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL) x = r.max_x + 3
def draw_face(self, diameter, border, font_size): with ui.ImageContext(diameter, diameter) as ctx: ui.set_color('white') circle = ui.Path.oval(border/2, border/2, diameter-border, diameter-border) circle.line_width = border-1 circle.fill() ui.set_color('silver') with ui.GState(): ui.set_shadow((0, 0, 0, 0.35), 0, 1, 5.0) circle.stroke() angle = (-pi/2) + (pi*2)/12.0 for i in xrange(1, 13): number = str(i) x = diameter/2 + cos(angle) * (diameter/2 - font_size*1.2) y = diameter/2 + sin(angle) * (diameter/2 - font_size*1.2) font = ('HelveticaNeue-UltraLight', font_size) w, h = ui.measure_string(number, font=font) rect = (x-50, y-h/2, 100, h) ui.draw_string(number, rect=rect, font=font, alignment=ui.ALIGN_CENTER) angle += (pi*2.0)/12.0 return ctx.get_image()
def main(): images = photos.pick_image(multi=True, original=upload_originals, raw_data= upload_originals) if images is None: return for i, img in enumerate(images): print 'Uploading image %i/%i...' % (i+1, len(images)) if not upload_originals: b = BytesIO() img.save(b, 'JPEG', quality=jpeg_quality) data = b.getvalue() else: data = img r = requests.post('http://how-old.net/Home/Analyze?isTest=False', files={'file': ('someimage.jpg', data)}) d = json.loads(json.loads(r.text)) faces = d.get('Faces') ui_img = ui.Image.from_data(data) scale = result_size / max(ui_img.size) w, h = ui_img.size[0] * scale, ui_img.size[1] * scale with ui.ImageContext(w, h) as ctx: ui_img.draw(0, 0, w, h) for face in faces: rect = [float(face['faceRectangle'][key]) * scale for key in ['left', 'top', 'width', 'height']] caption_rect = (rect[0], rect[1], max(40, rect[2]), 16) ui.set_color((0, 0, 0, 0.5)) ui.Path.rect(*rect).stroke() ui.fill_rect(*caption_rect) attrs = face['attributes'] age = attrs['age'] if age % 1.0 == 0: age = int(age) caption = '%s (%s)' % (age, attrs['gender'][0]) ui.draw_string(caption, caption_rect, color='white') result_img = ctx.get_image() result_img.show() if faces: faces_str = ', '.join(['%s (%s)' % (face['attributes']['age'], face['attributes']['gender']) for face in faces]) print '%i face%s: %s' % (len(faces), 's' if len(faces) != 1 else '', faces_str) else: print 'No faces found' print 'Done'
def __init__(self): self.dropped_sprites = set() # Initialize the floor collision body: w = self.size[0] self.physics_body = sk.PhysicsBody.edge_loop_rect(0, -100, w, 100) # Draw and cache textures for all numbers: self.textures = {} for n in '0123456789:': w, h = s*2+10, s*2 with ui.ImageContext(w, h) as ctx: ui.draw_string(n, font=('AvenirNext-Regular', h*0.94), rect=(0, 0, w, h), color='white', alignment=ui.ALIGN_CENTER) img = ctx.get_image() self.textures[n] = sk.Texture(img) margin = (self.size[0] - 7 * s) / 2 self.clock_nodes = [] self.time_str = time.strftime('%H:%M:%S') # Create a sprite node for every character in the time string: for i, c in enumerate(self.time_str): sprite = sk.SpriteNode(self.textures[c]) sprite.position = i * s + margin, self.size[1] - 200 self.add_child(sprite) self.clock_nodes.append(sprite)
def __init__(self, width, height, label_range, x_position, **kwargs): with ui.ImageContext(width, height) as ctx: ui.set_color('white') x_axis_path = ui.Path.rect(0, height - x_position - 2, width, 2) x_axis_path.stroke() x_axis_path.fill() y_axis_path = ui.Path.rect(0, 0, 2, height) y_axis_path.stroke() y_axis_path.fill() for counter in range(label_range + 1): x = counter * (int(width / label_range)) x_axis_ticks_path = ui.Path.rect(x, height - x_position - 8, 2, 8) x_axis_ticks_path.stroke() x_axis_ticks_path.fill() ui.draw_string(str(counter), rect=(x + 5, (height - x_position) - 15, 15, 15), color='white') img = Texture(ctx.get_image()) SpriteNode.__init__(self, img, **kwargs)
def __init__(self): with open('words_en.data') as f: self.words = marshal.load(f) self.root = sk.Node() self.did_change_size(None) self.add_child(self.root) textures = {} for letter in letter_freq: with ui.ImageContext(tile_size, tile_size) as ctx: shadow = ui.Path.rounded_rect(0, 0, tile_size, tile_size, 5) ui.set_color('silver') shadow.fill() bg = ui.Path.rounded_rect(0, 0, tile_size, tile_size-4, 5) ui.set_color('white') bg.fill() font = ('AvenirNext-Regular', font_size) w, h = ui.measure_string(letter.upper(), font=font) x, y = (tile_size - w)/2, (tile_size - h)/2 ui.draw_string(letter.upper(), rect=(x, y, w, h), font=font, color='black') textures[letter] = sk.Texture(ctx.get_image()) self.tile_textures = textures self.tiles = [[None]*cols for i in xrange(rows)] for x, y in product(xrange(cols), xrange(rows)): letter = choice(letter_bag) s = sk.SpriteNode(self.tile_textures[letter]) s.user_info = {'letter': letter, 'x': x, 'y': y} pos_x = tile_size/2 + x*(tile_size+padding) pos_y = tile_size/2 + y*(tile_size+padding) if x % 2 != 0: pos_y += tile_size/2 s.position = pos_x, pos_y s.color_blend_factor = 1 s.color = 'white' self.tiles[y][x] = s self.root.add_child(s) self.selected = [] self.touched_tile = None
def draw_label(self): if not self.drawing_on: return if not self.label_on: return cr = ui.Rect(*self.bounds) ui.set_color('purple') s = str('{:.0%}'.format(self.v)) dim = ui.measure_string(s, max_width=cr.width, font=self.font, alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL) lb_rect = ui.Rect(0, 0, dim[0], dim[1]) lb_rect.center(cr.center()) ui.draw_string(s, lb_rect, font=self.font, color='black', alignment=ui.ALIGN_CENTER, line_break_mode=ui.LB_TRUNCATE_TAIL)
def __init__(self): with open('words_en.data') as f: self.words = marshal.load(f) self.root = sk.Node() self.add_child(self.root) self.background_color = '#0b1d28' textures = {} for letter in letter_freq: with ui.ImageContext(tile_size, tile_size) as ctx: shadow = ui.Path.rounded_rect(2, 2, tile_size-4, tile_size-4, 5) ui.set_color('silver') shadow.fill() bg = ui.Path.rounded_rect(2, 2, tile_size-4, tile_size-8, 5) ui.set_color('white') bg.fill() font = ('AvenirNext-Regular', font_size) w, h = ui.measure_string(letter.upper(), font=font) x, y = (tile_size - w)/2, (tile_size - h)/2 ui.draw_string(letter.upper(), rect=(x, y, w, h), font=font, color='black') textures[letter] = sk.Texture(ctx.get_image()) self.tile_textures = textures self.tiles = [] #[[None]*rows for i in xrange(cols)] for x, y in product(xrange(cols), xrange(rows)): s = self.create_tile(x, y) self.tiles.append(s) self.root.add_child(s) self.selected = [] self.touched_tile = None self.score_label = sk.LabelNode() self.score_label.font_name = 'AvenirNext-Regular' self.score_label.font_size = 50 self.score_label.h_align = sk.H_ALIGN_CENTER self.score_label.text = '0' self.score = 0 self.add_child(self.score_label) self.did_change_size(None)
def draw(self): self.tuning = self.currentstate['instrument'] self.root = self.currentstate['root'] self.chord = self.currentstate['chord'] if self.tuning: fretboard = ui.Path.rect(0, 0, self.fbWidth, self.fbHeight) ui.set_color('#4C4722') fretboard.fill() nut = ui.Path.rect(0,0,self.fbWidth,self.nutOffset) ui.set_color('#ECF8D7') nut.fill() ui.set_color('white') fretSpace = int((self.fbHeight - 2*self.nutOffset)/(self.numFrets)) for index in range(self.numFrets): yFret = self.fretDistance(self.scale,index+1) fret = ui.Path() fret.line_width = 3 fret.move_to(0,yFret) fret.line_to(self.fbWidth,yFret) fret.stroke() for index in [3,5,7,9]: markeryPos = self.fretboardYPos(index) marker= self.PathCenteredCircle(int(0.5*self.fbWidth), markeryPos, self.markerRadius) marker.fill() markery12 = markeryPos = self.fretboardYPos(12) for xfraction in [0.25,0.75]: marker= self.PathCenteredCircle(int(xfraction*self.fbWidth), markery12, self.markerRadius) marker.fill() #assume width is 1.5" and strings are 1/8" from edge numStrings,offset,ss = self.stringSpacing() self.nutPosition = [] ui.set_color('grey') for index in range(numStrings): xString = offset + index*ss string = ui.Path() string.line_width = 3 string.move_to(xString,0) string.line_to(xString,self.fbHeight) string.stroke() self.nutPosition.append((xString,int(0.5* self.nutOffset))) if self.ChordPositions: # if there are some, draw current fingering self.num_chords.text = "{}".format(len(self.ChordPositions)) self.chord_num.text = "{}".format(self.currentPosition+1) middle_field.text = 'of' fingering,chordTones,fretPositions = self.ChordPositions[self.currentPosition] ui.set_color('red') for string in fingering: x,y,chordtone,nutmarker = string if not nutmarker: ui.set_color('red') marker= self.PathCenteredCircle(x,y,self.fingerRadius) marker.fill() ui.set_color('white') size = ui.measure_string(chordtone,font=('AmericanTypewriter-Bold', 22),alignment=ui.ALIGN_CENTER) ui.draw_string(chordtone,(int(x-0.5*size[0]),int(y-0.5*size[1]),0,0), font=('AmericanTypewriter-Bold',22),alignment=ui.ALIGN_CENTER) else: size = ui.measure_string(chordtone,font=('AmericanTypewriter-Bold',26),alignment=ui.ALIGN_CENTER) ui.draw_string(chordtone,(int(x-0.5*size[0]),int(y-0.5*size[1]),0,0), font=('AmericanTypewriter-Bold',26),alignment=ui.ALIGN_CENTER,color='black') size = ui.measure_string(chordtone,font=('AmericanTypewriter-Bold',22),alignment=ui.ALIGN_CENTER) ui.draw_string(chordtone,(int(x-0.5*size[0]),int(y-0.5*size[1]),0,0), font=('AmericanTypewriter-Bold',22),alignment=ui.ALIGN_CENTER,color='red') elif self.root and self.chord: sound.play_effect('Woosh_1') self.chord_num.text = "Try dropping" middle_field.text = "root, 3rd" self.num_chords.text = "or 5th"
def draw(self): self.tuning = currentState['instrument'] self.root = currentState['root'] self.chord = currentState['chord'] try: self.key = currentState['root']['noteValue'] except: pass if self.tuning: fretboard = ui.Path.rect(0, 0, self.fbWidth, self.fbHeight) ui.set_color('#4C4722') fretboard.fill() nut = ui.Path.rect(0,0,self.fbWidth,self.nutOffset) ui.set_color('#ECF8D7') nut.fill() ui.set_color('white') fretSpace = int((self.fbHeight - 2*self.nutOffset)/(self.numFrets)) self.fretY = [0] for index in range(self.numFrets): yFret = self.fretDistance(self.scale,index+1) self.fretY.append(yFret) self.PrevFretY = yFret fret = ui.Path() fret.line_width = 3 fret.move_to(0,yFret) fret.line_to(self.fbWidth,yFret) fret.stroke() for index in [3,5,7,9]: markeryPos = self.fretboardYPos(index) marker= self.PathCenteredCircle(int(0.5*self.fbWidth), markeryPos, self.markerRadius) marker.fill() markery12 = markeryPos = self.fretboardYPos(12) for xfraction in [0.25,0.75]: marker= self.PathCenteredCircle(int(xfraction*self.fbWidth), markery12, self.markerRadius) marker.fill() #assume width is 1.5" and strings are 1/8" from edge numStrings,offset,ss = self.stringSpacing() self.nutPosition = [] ui.set_color('grey') self.stringX = [] for index in range(numStrings): xString = offset + index*ss self.stringX.append(xString) string = ui.Path() string.line_width = 3 string.move_to(xString,0) string.line_to(xString,self.fbHeight) string.stroke() self.nutPosition.append((xString,int(0.5* self.nutOffset))) if self.ChordPositions and self.cc_mode == 'C': # if there are some, draw current fingering self.num_chords.text = "{}".format(len(self.ChordPositions)) self.chord_num.text = "{}".format(self.currentPosition+1) middle_field.text = 'of' fingering,chordTones,fretPositions = self.ChordPositions[self.currentPosition] ui.set_color('red') for string in fingering: x,y,chordtone,nutmarker = string if not nutmarker: ui.set_color('red') marker= self.PathCenteredCircle(x,y,self.fingerRadius) marker.fill() ui.set_color('white') size = ui.measure_string(chordtone,font=('AmericanTypewriter-Bold', 22),alignment=ui.ALIGN_CENTER) ui.draw_string(chordtone,(int(x-0.5*size[0]),int(y-0.5*size[1]),0,0), font=('AmericanTypewriter-Bold',22),alignment=ui.ALIGN_CENTER) else: size = ui.measure_string(chordtone,font=('AmericanTypewriter-Bold',26),alignment=ui.ALIGN_CENTER) ui.draw_string(chordtone,(int(x-0.5*size[0]),int(y-0.5*size[1]),0,0), font=('AmericanTypewriter-Bold',26),alignment=ui.ALIGN_CENTER,color='black') size = ui.measure_string(chordtone,font=('AmericanTypewriter-Bold',22),alignment=ui.ALIGN_CENTER) ui.draw_string(chordtone,(int(x-0.5*size[0]),int(y-0.5*size[1]),0,0), font=('AmericanTypewriter-Bold',22),alignment=ui.ALIGN_CENTER,color='red') elif self.root and self.chord and self.cc_mode == 'C': sound.play_effect('Woosh_1') self.chord_num.text = "Try dropping" middle_field.text = "root, 3rd" self.num_chords.text = "or 5th" elif self.cc_mode == 'I':# identify mode for key in self.touched.keys(): values = self.touched[key] x = self.stringX[values[2]] y = self.fretboardYPos(values[3]) if values[3]: ui.set_color('red') marker= self.PathCenteredCircle(x,y,self.fingerRadius) marker.fill() else: y = self.nutPosition[0][1] size = ui.measure_string('O',font=('AmericanTypewriter-Bold',26),alignment=ui.ALIGN_CENTER) ui.draw_string('O',(int(x-0.5*size[0]),int(y-0.5*size[1]),0,0), font=('AmericanTypewriter-Bold',26),alignment=ui.ALIGN_CENTER,color='black') size = ui.measure_string('O',font=('AmericanTypewriter-Bold',22),alignment=ui.ALIGN_CENTER) ui.draw_string('O',(int(x-0.5*size[0]),int(y-0.5*size[1]),0,0), font=('AmericanTypewriter-Bold',22),alignment=ui.ALIGN_CENTER,color='red') elif self.cc_mode == 'S': # print out scale notes ui.set_color('red') if self.scale_notes: for i,string in enumerate(self.scale_notes): for fret,note in string: x = self.stringX[i] if fret == 1: y = self.fretboardYPos(fret) + 12 elif fret: y = self.fretboardYPos(fret) else: y = self.nutPosition[0][1] + self.fingerRadius*0.3 ui.set_color('red') if note == self.key: marker= self.PathCenteredSquare(x,y,self.fingerRadius) else: marker= self.PathCenteredCircle(x,y,self.fingerRadius) marker.fill() if self.scale_display_mode == 'tones': outchar = SCALENOTES[(note + 12 - self.key) % 12] else: outchar = re.split('/', NOTE_NAMES[note])[0] ui.set_color('white') size = ui.measure_string(outchar,font=('AmericanTypewriter-Bold', 22),alignment=ui.ALIGN_CENTER) ui.draw_string(outchar,(int(x-0.5*size[0]),int(y-0.5*size[1]),0,0), font=('AmericanTypewriter-Bold',22),alignment=ui.ALIGN_CENTER) if self.scaleFrets: # mark the scale notes for string,fretNote in self.scaleFrets: fret,note = fretNote scaleTone = SCALENOTES[(note + 12 - self.key) % 12] x = self.stringX[string] if fret == 1: y = self.fretboardYPos(fret) + 12 elif fret: y = self.fretboardYPos(fret) else: y = self.nutPosition[0][1] + self.fingerRadius*0.3 if scaleTone in ('R','b3','3','5','5#'): # scale tone ui.set_color('yellow') elif scaleTone in ('b7','7'): ui.set_color('green') else: ui.set_color('red') marker= self.PathCenteredCircle(x,y,self.fingerRadius + 10) marker.line_width = 3 marker.stroke() else: pass