python类RGBA的实例源码

__init__.py 文件源码 项目:sc-controller 作者: kozec 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def parse_rgba(col):
    """
    Parses color specified by #RRGGBBAA string.
    '#' and 'AA' is optional.
    """
    # Because GTK can parse everything but theese :(
    alpha = "FF"
    if not col.startswith("#"):
        col = "#" + col
    if len(col) > 7:
        col, alpha = col[0:7], col[7:]
    rgba = Gdk.RGBA()
    if not rgba.parse(col):
        log.warning("Failed to parse RGBA color: %s", col)
    rgba.alpha = float(int(alpha, 16)) / 255.0
    return rgba
widgets.py 文件源码 项目:mcg 作者: coderkun 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def set_fullscreen(self, active):
        if active:
            self._change_tracklist_size(TracklistSize.HIDDEN, False, False)
            self._cover_box.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 1))
            GObject.idle_add(self._resize_image)
            # Hide curser
            self._appwindow.get_window().set_cursor(
                Gdk.Cursor.new_from_name(Gdk.Display.get_default(), "none")
            )
        else:
            self._change_tracklist_size(self._tracklist_size, False, False)
            self._cover_box.override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 0))
            GObject.idle_add(self._resize_image)
            # Reset cursor
            self._appwindow.get_window().set_cursor(
                Gdk.Cursor.new_from_name(Gdk.Display.get_default(), "default")
            )
__main__.py 文件源码 项目:razerCommander 作者: GabMus 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def onVirtKeyClick(self, eventbox, eventbtn):
        key = self.rkb.getKey(eventbox.keyx, eventbox.keyy)
        if not key.isGhost:
            if self.pipetteTBtn.get_active():
                color = key.color
                self.customColorPicker.set_rgba(color)
                self.pipetteTBtn.set_active(False)
            elif self.clearTBtn.get_active():
                key.color = Gdk.RGBA(0, 0, 0)
                black_rgba = Gdk.RGBA(0, 0, 0)
                eventbox.override_background_color(
                    Gtk.StateType.NORMAL,
                    black_rgba
                )
            else:
                key.color = self.customColorPicker.get_rgba()
                eventbox.override_background_color(
                    Gtk.StateType.NORMAL,
                    self.customColorPicker.get_rgba()
                )
custom_kb_builder.py 文件源码 项目:razerCommander 作者: GabMus 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def build_keyrow_box(row, colors, signal_handler, prof_index):
    box = Gtk.Box(orientation=Gtk.Orientation.HORIZONTAL)
    for key in row.keylist:
        if not key.isGhost:
            k_col = Gdk.RGBA(
                colors[prof_index][0],
                colors[prof_index][1],
                colors[prof_index][2]
            )
        else:
            k_col = Gdk.RGBA(0, 0, 0)
        keybox = build_key_box(
            key,
            k_col,
            signal_handler
        )
        if not key.isGhost:
            prof_index += 1
        box.pack_start(keybox, True, True, 0)
    return {'row': box, 'prof_index': prof_index}
table.py 文件源码 项目:MTTT 作者: roxana-lafuente 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def cell_in_translation_table_changed(self, text_buffer_object, segment_index):
        if not self.REC_button.get_active():
            self.save_post_editing_changes_button.show()
        elif segment_index != self.last_segment_changed:
            self.save_function()
            self.last_segment_changed = segment_index

        def fix_text(text):
            #in case the user deleted the endline character at the end of the text segment
            new_line_index = text.rfind("\n")
            if new_line_index == -1:
                text += "\n"
            return text
        text = fix_text(text_buffer_object.get_text(text_buffer_object.get_start_iter(),text_buffer_object.get_end_iter(),True) )
        self.tables_content[self.reference_text_lines][segment_index] = text
        self.translation_reference_text_TextViews_modified_flag[segment_index] = text
        self.tables_content[self.reference_text_views][segment_index].override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0.7, 249, 249, 240))
table.py 文件源码 项目:MTTT 作者: roxana-lafuente 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def create_cell(self, text_line_type, text_view_type, row_index, editable):
        cell = Gtk.TextView()
        cell.set_editable(editable)
        cell.set_cursor_visible(editable)
        cellTextBuffer = cell.get_buffer()
        index = row_index + self.tables_content[self.table_index]
        text = textwrap.fill(self.tables_content[text_line_type][index].rstrip('\n'), width=40)
        cellTextBuffer.set_text(text)
        cellTextBuffer.create_tag("#F8CBCB",background="#F8CBCB")
        cellTextBuffer.create_tag("#A6F3A6",background="#A6F3A6")
        self.tables_content[text_view_type][index] = cell
        if self.table_type == "translation_table":
            cellTextBuffer.connect("changed", self.cell_in_translation_table_changed, index)
            cell.connect("button-press-event", self.cell_in_translation_table_is_being_focused, index)
            if index in self.translation_reference_text_TextViews_modified_flag:
                self.tables_content[self.reference_text_views][index].override_background_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0.7, 249, 249, 240))

        cell.set_right_margin(20)
        cell.show()
        self.table.attach(
        cell,
        text_line_type + 1,
        text_line_type + 2,
        row_index + 1,
        row_index + 2)
drawing.py 文件源码 项目:x-mario-center 作者: fossasia 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def mix(fgcolor, bgcolor, mix_alpha):
    """ Creates a composite rgb of a foreground rgba and a background rgb.

         - fgcolor: an rgb of floats
         - bgcolor: an rgb of floats
         - mix_alpha: (0.0 - 1.0) the proportion of fgcolor mixed
                      into bgcolor
    """

    src_r, src_g, src_b = fgcolor.red, fgcolor.green, fgcolor.blue
    bg_r, bg_g, bg_b = bgcolor.red, bgcolor.green, bgcolor.blue

    # Source: http://en.wikipedia.org/wiki/Alpha_compositing
    r = ((1 - mix_alpha) * bg_r) + (mix_alpha * src_r)
    g = ((1 - mix_alpha) * bg_g) + (mix_alpha * src_g)
    b = ((1 - mix_alpha) * bg_b) + (mix_alpha * src_b)
    return Gdk.RGBA(red=r, green=g, blue=b)
drawing.py 文件源码 项目:x-mario-center 作者: fossasia 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def mix(fgcolor, bgcolor, mix_alpha):
    """ Creates a composite rgb of a foreground rgba and a background rgb.

         - fgcolor: an rgb of floats
         - bgcolor: an rgb of floats
         - mix_alpha: (0.0 - 1.0) the proportion of fgcolor mixed
                      into bgcolor
    """

    src_r, src_g, src_b = fgcolor.red, fgcolor.green, fgcolor.blue
    bg_r, bg_g, bg_b = bgcolor.red, bgcolor.green, bgcolor.blue

    # Source: http://en.wikipedia.org/wiki/Alpha_compositing
    r = ((1 - mix_alpha) * bg_r) + (mix_alpha * src_r)
    g = ((1 - mix_alpha) * bg_g) + (mix_alpha * src_g)
    b = ((1 - mix_alpha) * bg_b) + (mix_alpha * src_b)
    return Gdk.RGBA(red=r, green=g, blue=b)
games_nebula.py 文件源码 项目:games_nebula 作者: yancharkin 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def parse_goglib_colors(self):
        self.goglib_include_rgba = Gdk.RGBA()
        self.goglib_include_rgba.parse(self.goglib_include_color)
        self.goglib_exclude_rgba = Gdk.RGBA()
        self.goglib_exclude_rgba.parse(self.goglib_exclude_color)
games_nebula.py 文件源码 项目:games_nebula 作者: yancharkin 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def parse_mylib_colors(self):
        self.mylib_include_rgba = Gdk.RGBA()
        self.mylib_include_rgba.parse(self.mylib_include_color)
        self.mylib_exclude_rgba = Gdk.RGBA()
        self.mylib_exclude_rgba.parse(self.mylib_exclude_color)
common.py 文件源码 项目:aniwall 作者: worron 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def hex_from_rgba(rgba):
    """Translate color from Gdk.RGBA to html hex format"""
    return "#%02X%02X%02X" % tuple([int(getattr(rgba, name) * 255) for name in ("red", "green", "blue")])
common.py 文件源码 项目:aniwall 作者: worron 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def rgba_from_hex(hex_):
    """Translate color from html hex to Gdk.RGBA"""
    color = Gdk.RGBA()
    color.parse(hex_)
    return color
mooncalendarwindow.py 文件源码 项目:my-weather-indicator 作者: atareao 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def set_date(self):
        self.headerbar.set_subtitle(self.adate.strftime('%B - %Y'))
        fdom = first_day_of_month(self.adate)
        adate = self.adate.replace(day=1)
        for row in range(1, 7):
            wd = adate + datetime.timedelta(days=7 * (row - 1))
            self.week_days[row].set_text(str(wd.isocalendar()[1]))
        max = {'position': -1, 'value': 0}
        med = {'position': -1, 'value': 1}
        min = {'position': -1, 'value': 1}
        for contador in range(0, 42):
            if contador < fdom:
                tadate = adate - datetime.timedelta(days=(fdom - contador))
            else:
                tadate = adate + datetime.timedelta(days=(contador - fdom))
            self.days[contador].set_date(tadate)
            if tadate.month != adate.month:
                self.days[contador].override_background_color(
                    Gtk.StateFlags.NORMAL, Gdk.RGBA(.5, .5, .5, 1))
            elif tadate.date() == datetime.datetime.today().date():
                self.days[contador].override_background_color(
                    Gtk.StateFlags.NORMAL, Gdk.RGBA(1.0, 0.0, 0.0, 1))
            else:
                self.days[contador].override_background_color(
                    Gtk.StateFlags.NORMAL, Gdk.RGBA(1., 1., 1., 1))
            if tadate.month == adate.month:
                if self.days[contador].get_position() >= max['value']:
                    max['position'] = contador
                    max['value'] = self.days[contador].get_position()
                if self.days[contador].get_position() <= min['value']:
                    min['position'] = contador
                    min['value'] = self.days[contador].get_position()
                if abs(float(self.days[contador].get_position()) - .5) <=\
                        (med['value']):
                    med['position'] = contador
                    med['value'] = abs(float(
                        self.days[contador].get_position()) - 0.5)
        self.days[med['position']].override_background_color(
            Gtk.StateFlags.NORMAL, Gdk.RGBA(0.0, 0.5, 0.0, 1))
        self.days[min['position']].override_background_color(
            Gtk.StateFlags.NORMAL, Gdk.RGBA(0.5, 0.0, 0.5, 1))
window.py 文件源码 项目:nvim-pygtk3 作者: rliang 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def update_color(self, bg_color: str, is_dark: bool):
        """Updates the widget's background color and theme.

        :bg_color: string representing the color, or 'None'.
        :is_dark: whether the background is dark, see `:h background`.

        """
        self.get_settings().props.gtk_application_prefer_dark_theme = is_dark
        if bg_color != 'None':
            rgba = Gdk.RGBA()
            rgba.parse(bg_color)
            self.set_color_background(rgba)
        else:
            GLib.idle_add(self.reset_color)
widgets.py 文件源码 项目:mcg 作者: coderkun 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def __init__(self, builder):
        GObject.GObject.__init__(self)

        self._current_album = None
        self._cover_pixbuf = None
        self._timer = None
        self._properties = {}
        self._tracklist_size = TracklistSize.LARGE
        self._icon_theme = Gtk.IconTheme.get_default()

        # Widgets
        self._appwindow = builder.get_object('appwindow')
        self._panel = builder.get_object('cover-panel')
        self._toolbar = builder.get_object('cover-toolbar')
        # Toolbar menu
        self._toolbar_tracklist = builder.get_object('cover-toolbar-tracklist')
        self._toolbar_tracklist_buttons = {
            TracklistSize.LARGE: builder.get_object('cover-toolbar-tracklist-large'),
            TracklistSize.SMALL: builder.get_object('cover-toolbar-tracklist-small'),
            TracklistSize.HIDDEN: builder.get_object('cover-toolbar-tracklist-hidden')
        }
        # Cover
        self._cover_stack = builder.get_object('cover-stack')
        self._cover_spinner = builder.get_object('cover-spinner')
        self._cover_scroll = builder.get_object('cover-scroll')
        self._cover_box = builder.get_object('cover-box')
        self._cover_image = builder.get_object('cover-image')
        self._cover_stack.set_visible_child(self._cover_scroll)
        self._cover_pixbuf = self._get_default_image()
        # Album Infos
        self._info_revealer = builder.get_object('cover-info-revealer')
        self._info_box = builder.get_object('cover-info-box')
        self._album_title_label = builder.get_object('cover-album')
        self._album_date_label = builder.get_object('cover-date')
        self._album_artist_label = builder.get_object('cover-artist')
        # Songs
        self._songs_scale = builder.get_object('cover-songs')
        self._songs_scale.override_color(Gtk.StateFlags.NORMAL, Gdk.RGBA(0, 0, 0, 1))

        # Initial actions
        GObject.idle_add(self._enable_tracklist)
Config.py 文件源码 项目:bcloud 作者: wangYanJava 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def load_color_schema():
    if not os.path.exists(COLOR_SCHEMA):
        return []
    with open(COLOR_SCHEMA) as fh:
        color_list = json.load(fh)

    schema = []
    for color in color_list:
        rgba = Gdk.RGBA()
        rgba.red = int(color[:2], base=16) / 255
        rgba.green = int(color[2:4], base=16) / 255
        rgba.blue = int(color[4:6], base=16) / 255
        rgba.alpha = int(color[6:], base=16) / 255
        schema.append(rgba)
    return schema
util.py 文件源码 项目:luminance 作者: craigcabrey 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def hsv_to_gdk_rgb(hue, sat, bri):
    rgb = colorsys.hsv_to_rgb(
        hue / 65535,
        sat / 255,
        bri / 255
    )

    return Gdk.RGBA(red=rgb[0], green=rgb[1], blue=rgb[2])
theme_creator.py 文件源码 项目:XFWM_theme_creator 作者: Sjc1000 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __init__(self):
        Gtk.ColorButton.__init__(self)
        self.set_rgba(Gdk.RGBA(0, 0, 0, 1))
        self.connect('color-set', self.color_set)
theme_creator.py 文件源码 项目:XFWM_theme_creator 作者: Sjc1000 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def __init__(self):
        Gtk.ColorButton.__init__(self)
        self.set_rgba(Gdk.RGBA(1, 1, 1, 1))
        self.connect('color-set', self.color_set)
autocolor.py 文件源码 项目:cavalcade 作者: worron 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def color_setup(self, conn, flag):
        """Read data from resent calculation and transform it to rgba color"""
        if flag == GLib.IO_IN:
            color_values = conn.recv()
            rgba = Gdk.RGBA(*color_values, self.config["color"]["autofg"].alpha)
            self.emit("ac-update", rgba)
            return True
        else:
            logger.error("Autocolor multiprocessing error: connection was unexpectedy terminated")
            self.watcher = None
canvas.py 文件源码 项目:cavalcade 作者: worron 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def _set_bgpaint(self, value):
        """Use solid color or transparent background"""
        self.config["window"]["bgpaint"] = value
        rgba = self.config["color"]["bg"] if value else Gdk.RGBA(0, 0, 0, 0)
        self.set_bg_rgba(rgba)
config.py 文件源码 项目:cavalcade 作者: worron 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def str_to_rgba(hex_):
    """Translate color from hex string to Gdk.RGBA"""
    purehex = hex_.lstrip("#")
    nums = [int(purehex[i:i + 2], 16) / 255.0 for i in range(0, 7, 2)]
    return Gdk.RGBA(*nums)
config.py 文件源码 项目:cavalcade 作者: worron 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def rgba_to_str(rgba):
    """Translate color from Gdk.RGBA to hex format"""
    return "#%02X%02X%02X%02X" % tuple(int(getattr(rgba, name) * 255) for name in ("red", "green", "blue", "alpha"))
config.py 文件源码 项目:cavalcade 作者: worron 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def __init__(self, name, pattern={}):
        self.name = name
        self.pattern = pattern
        self.is_fallback = False

        # read functions
        self.reader = {
            int: lambda section, option: self.parser.getint(section, option),
            bool: lambda section, option: self.parser.getboolean(section, option),
            str: lambda section, option: self.parser.get(section, option),
            float: lambda section, option: self.parser.getfloat(section, option),
            "ilist": lambda section, option: [int(v.strip()) for v in self.parser.get(section, option).split(";")],
            "hint": lambda section, option: getattr(Gdk.WindowTypeHint, self.parser.get(section, option)),
            Gdk.RGBA: lambda section, option: str_to_rgba(self.parser.get(section, option)),
        }

        # write functions
        self.writer = {
            int: lambda value: str(value),
            bool: lambda value: str(int(value)),
            str: lambda value: value,
            float: lambda value: "{:.2f}".format(value),
            "ilist": lambda value: ";".join(str(i) for i in value),
            "hint": lambda value: value.value_nick.upper(),
            Gdk.RGBA: lambda value: rgba_to_str(value),
        }

        # init
        self._init_config_file()
        self._load_config_file()
labels.py 文件源码 项目:paperwork-backend 作者: openpaperwork 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def _get_color(self):
        color = Gdk.RGBA()
        color.parse(self._color)
        return color
guisupport.py 文件源码 项目:ACYLS 作者: worron 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def hex_from_rgba(rgba):
    """Translate color from Gdk.RGBA to html hex format"""
    return "#%02X%02X%02X" % tuple([int(getattr(rgba, name) * 255) for name in ("red", "green", "blue")])
colorpage.py 文件源码 项目:ACYLS 作者: worron 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def build_data_stores(self):
        """Build stores for GUI dataviews"""
        self.store = dict()

        # custom icons
        self.ied = {'Name': 0, 'State': 1}
        self.store['custom_icons'] = Gtk.ListStore(str, bool)
        self.store['custom_icons'].append(["Simple Icon Group", False])

        renderer_toggle = Gtk.CellRendererToggle()
        renderer_toggle.connect("toggled", self.on_custom_icon_toggled)

        self.gui['custom_icons_treeview'].append_column(Gtk.TreeViewColumn("Name", Gtk.CellRendererText(), text=0))
        self.gui['custom_icons_treeview'].append_column(Gtk.TreeViewColumn("State", renderer_toggle, active=1))
        self.gui['custom_icons_treeview'].set_model(self.store['custom_icons'])

        # color list
        self.ced = {'Color': 0, 'Alpha': 1, 'Offset': 2, 'RGBA': 3}
        colorstore_visible_keys = [k for k in self.ced.keys() if k != 'RGBA']

        self.store['colorlist'] = Gtk.ListStore(str, float, int, str)
        for key in sorted(colorstore_visible_keys, key=lambda k: self.ced[k]):
            self.gui['colorlist_treeview'].append_column(
                Gtk.TreeViewColumn(key, Gtk.CellRendererText(), text=self.ced[key])
            )
        self.gui['colorlist_treeview'].set_model(self.store['colorlist'])

        # gradient direction
        self.ded = {'Coord': 0, 'Value': 1}
        self.store['direction'] = Gtk.ListStore(str, int)
        self.gui['renderer_spin'] = Gtk.CellRendererSpin(editable=True, adjustment=Gtk.Adjustment(0, 0, 100, 5, 0, 0))
        self.signals['direction_edited'] = self.gui['renderer_spin'].connect("edited", self.on_direction_edited)

        self.gui['direction_treeview'].append_column(Gtk.TreeViewColumn("Coord", Gtk.CellRendererText(), text=0))
        self.gui['direction_treeview'].append_column(Gtk.TreeViewColumn("Value", self.gui['renderer_spin'], text=1))
        self.gui['direction_treeview'].set_model(self.store['direction'])
colorpage.py 文件源码 项目:ACYLS 作者: worron 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def on_color_selection_changed(self, selection):
        model, sel = selection.get_selected()

        if sel is not None:
            self.color_selected = sel
            rgba = Gdk.RGBA()
            rgba.parse(model[sel][self.ced['RGBA']])
            rgba.alpha = model[sel][self.ced['Alpha']]
            self.gui['color_selector'].set_current_rgba(rgba)

            offset = model[sel][self.ced['Offset']]
            self.gui['offset_scale'].set_value(offset)
colorpage.py 文件源码 项目:ACYLS 作者: worron 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def on_color_change(self, *args):
        rgba = self.gui['color_selector'].get_current_rgba()
        self.store['colorlist'].set_value(self.color_selected, self.ced['Color'], hex_from_rgba(rgba))
        self.store['colorlist'].set_value(self.color_selected, self.ced['Alpha'], rgba.alpha)
        self.store['colorlist'].set_value(self.color_selected, self.ced['RGBA'], rgba.to_string())
        self.refresh()
filters.py 文件源码 项目:ACYLS 作者: worron 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def gui_settler_color(self, button, color, alpha=None):
        """GUI setup helper - color"""
        rgba = Gdk.RGBA()
        rgba.parse(self.param[color].match())
        if alpha is not None:
            rgba.alpha = float(self.param[alpha].match())
        self.gui[button].set_rgba(rgba)

    # Handler generators


问题


面经


文章

微信
公众号

扫码关注公众号