1680244740
Happy Pi Day! Does counting pixels get you the circumference of a circle?
For Pi Day this year, I wanted to write a program to calculate pi by drawing a circle in FreeDOS graphics mode, then counting pixels to estimate the circumference. I naively assumed that this would give me an approximation of pi. I didn't expect to get 3.14, but I thought the value would be somewhat close to 3.0.
I was wrong. Estimating the circumference of a circle by counting the pixels required to draw it will give you the wrong result. No matter what resolution I tried, the final pi calculation of circumference divided by diameter was always around 2.8.
I wrote a FreeDOS program using OpenWatcom C that draws a circle to the screen, then counts the pixels that make up that circle. I wrote it in FreeDOS because DOS programs can easily enter graphics mode by using the OpenWatcom _setvideomode
function. The _VRES16COLOR
video mode puts the display into 640×480 resolution at 16 colors, a common "classic VGA" screen resolution. In the standard 16 color DOS palette, color 0 is black, color 1 is blue, color 7 is a low intensity white, and color 15 is a high intensity white.
In graphics mode, you can use the _ellipse
function to draw an ellipse to the screen, from some starting x,y coordinate in the upper left to a final x,y coordinate in the lower right. If the height and width are the same, the ellipse is a circle. Note that in graphics mode, x and y count from zero, so the upper left corner is always 0,0.
(Jim Hall, CC BY-SA 4.0)
You can use the _getpixel
function to get the color of a pixel at a specified x,y coordinate on the screen. To show the progress in my program, I also used the _setpixel
function to paint a single pixel at any x,y on the screen. When the program found a pixel that defined the circle, I changed that pixel to bright white. For other pixels, I set the color to blue.
(Jim Hall, CC BY-SA 4.0)
With these graphics functions, you can write a program that draws a circle to the screen, then iterates over all the x,y coordinates of the circle to count the pixels. For any pixel that is color 7 (the color of the circle), add one to the pixel count. At the end, you can use the total pixel count as an estimate of the circumference:
#include <stdio.h>
#include <graph.h>
int
main()
{
unsigned long count;
int x, y;
/* draw a circle */
_setvideomode(_VRES16COLOR); /* 640x480 */
_setcolor(7); /* white */
_ellipse(_GBORDER, 0, 0, 479, 479);
/* count pixels */
count = 0;
for (x = 0; x <= 479; x++) {
for (y = 0; y <= 479; y++) {
if (_getpixel(x, y) == 7) {
count++;
/* highlight the pixel */
_setcolor(15); /* br white */
_setpixel(x, y);
}
else {
/* highlight the pixel */
_setcolor(1); /* blue */
_setpixel(x, y);
}
}
}
/* done */
_setvideomode(_DEFAULTMODE);
printf("pixel count (circumference?) = %lu\n", count);
puts("diameter = 480");
printf("pi = c/d = %f\n", (double) count / 480.0);
return 0;
}
But counting pixels to determine the circumference underestimates the actual circumference of the circle. Because pi is the ratio of the circumference of a circle to its diameter, my pi calculation was noticeably lower than 3.14. I tried several video resolutions, and I always got a final result of about 2.8:
pixel count (circumference?) = 1356
diameter = 480
pi = c/d = 2.825000
The problem with counting pixels to estimate the circumference is that the pixels are only a sample of a circular drawing. Pixels are discrete points in a grid, while a circle is a continuous drawing. To provide a better estimate of the circumference, you must measure the distance between pixels and use that total measurement for the circumference.
To update the program, you must write a function that calculates the distance between any two pixels: x0,y0 and x,y. You don't need a bunch of fancy math or algorithms here, just the knowledge that the OpenWatcom _ellipse
function draws only solid pixels in the color you set for the circle. The function doesn't attempt to provide antialiasing by drawing nearby pixels in some intermediate color. That allows you to simplify the math. In a circle, pixels are always directly adjacent to one another: vertically, horizontally, or diagonally.
For pixels that are vertically or horizontally adjacent, the pixel "distance" is simple. It's a distance of 1.
For pixels that are diagonally adjacent, you can use the Pythagorean theorem of a²+b²=c² to calculate the distance between two diagonal pixels as the square root of 2, or approximately 1.414.
double
pixel_dist(int x0, int y0, int x, int y)
{
if (((x - x0) == 0) && ((y0 - y) == 1)) {
return 1.0;
}
if (((y0 - y) == 0) && ((x - x0) == 1)) {
return 1.0;
}
/* if ( ((y0-y)==1) && ((x-x0)==1) ) { */
return 1.414;
/* } */
}
I wrapped the last "if" statement in comments so you can see what the condition is supposed to represent.
To measure the circumference, we don't need to examine the entire circle. We can save a little time and effort by working on only the upper left quadrant. This also allows us to know the starting coordinate of the first pixel in the circle; we'll skip the first pixel at 0,239 and instead assume that as our first x0,y0 coordinate in measuring the quarter-circumference.
(Jim Hall, CC BY-SA 4.0)
The final program is similar to our "count the pixels" program, but instead measures the tiny distances between pixels in the upper left quadrant of the circle. You may notice that the program counts down the y coordinates, from 238 to 0. This accommodates the assumption that the known starting x0,y0 coordinate in the quarter-circle is 0,239. With that assumption, the program only needs to evaluate the y coordinates between 0 and 238. To estimate the total circumference of the circle, multiply the quarter-measurement by 4:
#include <stdio.h>
#include <graph.h>
double
pixel_dist(int x0, int y0, int x, int y)
{
...
}
int
main()
{
double circum;
int x, y;
int x0, y0;
/* draw a circle */
_setvideomode(_VRES16COLOR); /* 640x480 */
_setcolor(7); /* white */
_ellipse(_GBORDER, 0, 0, 479, 479);
/* calculate circumference, use upper left quadrant only */
circum = 0.0;
x0 = 0;
y0 = 479 / 2;
for (x = 0; x <= 479 / 2; x++) {
for (y = (479 / 2) - 1; y >= 0; y--) {
if (_getpixel(x, y) == 7) {
circum += pixel_dist(x0, y0, x, y);
x0 = x;
y0 = y;
/* highlight the pixel */
_setcolor(15); /* br white */
_setpixel(x, y);
}
else {
/* highlight the pixel */
_setcolor(1); /* blue */
_setpixel(x, y);
}
}
}
circum *= 4.0;
/* done */
_setvideomode(_DEFAULTMODE);
printf("circumference = %f\n", circum);
puts("diameter = 480");
printf("pi = c/d = %f\n", circum / 480.0);
return 0;
}
This provides a better estimate of the circumference. It's still off by a bit, because measuring a circle using pixels is still a pretty rough approximation, but the final pi calculation is much closer to the expected value of 3.14:
circumference = 1583.840000
diameter = 480
pi = c/d = 3.299667
Original article source at: https://opensource.com/
1680223560
С Днем Пи! Подсчет пикселей дает вам длину окружности?
В этом году ко Дню Пи я хотел написать программу для вычисления числа Пи путем рисования круга в графическом режиме FreeDOS , а затем подсчета пикселей для оценки длины окружности. Я наивно полагал, что это даст мне приблизительное число пи. Я не ожидал получить 3,14, но думал, что значение будет близко к 3,0.
Я был неправ. Оценка окружности круга путем подсчета пикселей, необходимых для его рисования, даст неверный результат. Независимо от того, какое разрешение я пробовал, окончательный расчет пи длины окружности, деленной на диаметр, всегда был около 2,8.
Я написал программу FreeDOS, используя OpenWatcom C, которая рисует круг на экране, а затем считает пиксели, составляющие этот круг. Я написал его в FreeDOS, потому что программы DOS могут легко войти в графический режим с помощью _setvideomodeфункции OpenWatcom. Видеорежим _VRES16COLORпереводит дисплей в разрешение 640 × 480 с 16 цветами, обычное «классическое разрешение экрана VGA». В стандартной 16-цветной палитре DOS цвет 0 — черный, цвет 1 — синий, цвет 7 — белый с низкой интенсивностью, а цвет 15 — белый с высокой интенсивностью.
В графическом режиме вы можете использовать эту _ellipseфункцию для рисования эллипса на экране от некоторой начальной координаты x,y в левом верхнем углу до конечной координаты x,y в правом нижнем углу. Если высота и ширина одинаковы, эллипс является окружностью. Обратите внимание, что в графическом режиме x и y отсчитываются от нуля, поэтому верхний левый угол всегда равен 0,0.
(Джим Холл, CC BY-SA 4.0)
Вы можете использовать эту _getpixelфункцию, чтобы получить цвет пикселя в указанной координате x, y на экране. Чтобы показать прогресс в моей программе, я также использовал _setpixelфункцию для рисования одного пикселя в любых x, y на экране. Когда программа нашла пиксель, определяющий круг, я изменил этот пиксель на ярко-белый. Для других пикселей я установил синий цвет.
(Джим Холл, CC BY-SA 4.0)
С помощью этих графических функций вы можете написать программу, которая рисует круг на экране, а затем перебирает все координаты круга x,y для подсчета пикселей. Для любого пикселя цвета 7 (цвета круга) добавьте единицу к количеству пикселей. В конце вы можете использовать общее количество пикселей в качестве оценки окружности:
#include <stdio.h>
#include <graph.h>
int
main()
{
unsigned long count;
int x, y;
/* draw a circle */
_setvideomode(_VRES16COLOR); /* 640x480 */
_setcolor(7); /* white */
_ellipse(_GBORDER, 0, 0, 479, 479);
/* count pixels */
count = 0;
for (x = 0; x <= 479; x++) {
for (y = 0; y <= 479; y++) {
if (_getpixel(x, y) == 7) {
count++;
/* highlight the pixel */
_setcolor(15); /* br white */
_setpixel(x, y);
}
else {
/* highlight the pixel */
_setcolor(1); /* blue */
_setpixel(x, y);
}
}
}
/* done */
_setvideomode(_DEFAULTMODE);
printf("pixel count (circumference?) = %lu\n", count);
puts("diameter = 480");
printf("pi = c/d = %f\n", (double) count / 480.0);
return 0;
}
Но подсчет пикселей для определения окружности занижает реальную окружность круга. Поскольку пи — это отношение длины окружности к ее диаметру, мое вычисление числа пи было заметно ниже 3,14. Я пробовал несколько разрешений видео и всегда получал конечный результат около 2,8:
pixel count (circumference?) = 1356
diameter = 480
pi = c/d = 2.825000
Проблема с подсчетом пикселей для оценки окружности заключается в том, что пиксели являются лишь образцом кругового рисунка. Пиксели — это отдельные точки в сетке, а круг — это непрерывный рисунок. Чтобы обеспечить более точную оценку окружности, вы должны измерить расстояние между пикселями и использовать это общее значение для окружности.
Для обновления программы необходимо написать функцию, вычисляющую расстояние между любыми двумя пикселями: x0,y0 и x,y. Здесь вам не нужна куча причудливой математики или алгоритмов, просто знайте, что _ellipseфункция OpenWatcom рисует только сплошные пиксели того цвета, который вы установили для круга. Функция не пытается обеспечить сглаживание , рисуя близлежащие пиксели каким-либо промежуточным цветом. Это позволяет упростить математику. В круге пиксели всегда непосредственно примыкают друг к другу: по вертикали, горизонтали или диагонали.
Для пикселей, которые являются смежными по вертикали или горизонтали, «расстояние» пикселя простое. Это расстояние 1 .
Для пикселей, смежных по диагонали, вы можете использовать теорему Пифагора a²+b²=c², чтобы вычислить расстояние между двумя диагональными пикселями как квадратный корень из 2 или приблизительно 1,414 .
double
pixel_dist(int x0, int y0, int x, int y)
{
if (((x - x0) == 0) && ((y0 - y) == 1)) {
return 1.0;
}
if (((y0 - y) == 0) && ((x - x0) == 1)) {
return 1.0;
}
/* if ( ((y0-y)==1) && ((x-x0)==1) ) { */
return 1.414;
/* } */
}
Я обернул последнее выражение «если» в комментарии, чтобы вы могли видеть, что должно представлять условие.
Чтобы измерить окружность, нам не нужно исследовать весь круг. Мы можем сэкономить немного времени и сил, работая только с верхним левым квадрантом. Это также позволяет нам узнать начальную координату первого пикселя в круге; мы пропустим первый пиксель в 0,239 и вместо этого предположим, что это наша первая координата x0,y0 при измерении четверти окружности.
(Джим Холл, CC BY-SA 4.0)
Окончательная программа похожа на нашу программу «подсчет пикселей», но вместо этого измеряет крошечные расстояния между пикселями в верхнем левом квадранте круга. Вы можете заметить, что программа отсчитывает координаты y от 238 до 0. Это соответствует предположению, что известная начальная координата x0,y0 в четверти окружности равна 0,239. При таком предположении программе нужно только оценить координаты y в диапазоне от 0 до 238. Чтобы оценить общую длину окружности, умножьте четверть измерения на 4:
#include <stdio.h>
#include <graph.h>
double
pixel_dist(int x0, int y0, int x, int y)
{
...
}
int
main()
{
double circum;
int x, y;
int x0, y0;
/* draw a circle */
_setvideomode(_VRES16COLOR); /* 640x480 */
_setcolor(7); /* white */
_ellipse(_GBORDER, 0, 0, 479, 479);
/* calculate circumference, use upper left quadrant only */
circum = 0.0;
x0 = 0;
y0 = 479 / 2;
for (x = 0; x <= 479 / 2; x++) {
for (y = (479 / 2) - 1; y >= 0; y--) {
if (_getpixel(x, y) == 7) {
circum += pixel_dist(x0, y0, x, y);
x0 = x;
y0 = y;
/* highlight the pixel */
_setcolor(15); /* br white */
_setpixel(x, y);
}
else {
/* highlight the pixel */
_setcolor(1); /* blue */
_setpixel(x, y);
}
}
}
circum *= 4.0;
/* done */
_setvideomode(_DEFAULTMODE);
printf("circumference = %f\n", circum);
puts("diameter = 480");
printf("pi = c/d = %f\n", circum / 480.0);
return 0;
}
Это обеспечивает лучшую оценку окружности. Это все еще немного отличается, потому что измерение круга с помощью пикселей по-прежнему является довольно грубым приближением, но окончательный расчет числа пи намного ближе к ожидаемому значению 3,14:
circumference = 1583.840000
diameter = 480
pi = c/d = 3.299667
Оригинальный источник статьи: https://opensource.com/
1680219840
圆周率日快乐!计算像素可以得到圆周长吗?
今年的圆周率日,我想写一个程序来计算圆周率,在FreeDOS图形模式下画一个圆,然后计算像素来估计周长。我天真地假设这会给我一个 pi 的近似值。我没想到会得到3.14,但我认为这个值会有点接近3.0。
我错了。通过计算绘制圆所需的像素来估计圆的周长会给您错误的结果。无论我尝试什么分辨率,最终圆周率除以直径的圆周率计算总是在 2.8 左右。
我使用 OpenWatcom C 编写了一个 FreeDOS 程序,该程序在屏幕上绘制一个圆圈,然后计算构成该圆圈的像素。我是用FreeDOS写的,因为DOS程序可以很容易的通过OpenWatcom_setvideomode功能进入图形模式。视频_VRES16COLOR模式将显示器设置为 640×480 分辨率和 16 色,这是一种常见的“经典 VGA”屏幕分辨率。在标准的 16 色 DOS 调色板中,颜色 0 为黑色,颜色 1 为蓝色,颜色 7 为低强度白色,颜色 15 为高强度白色。
在图形模式下,您可以使用该_ellipse函数在屏幕上绘制一个椭圆,从左上角的某个起始 x,y 坐标到右下角的最终 x,y 坐标。如果高和宽相同,椭圆就是圆。请注意,在图形模式下,x 和 y 从零开始计数,因此左上角始终为 0,0。
(吉姆·霍尔,CC BY-SA 4.0)
您可以使用该_getpixel函数获取屏幕上指定 x,y 坐标处像素的颜色。为了在我的程序中显示进度,我还使用该_setpixel函数在屏幕上的任意 x、y 处绘制单个像素。当程序找到定义圆的像素时,我将该像素更改为亮白色。对于其他像素,我将颜色设置为蓝色。
(吉姆·霍尔,CC BY-SA 4.0)
使用这些图形函数,您可以编写一个程序在屏幕上绘制一个圆,然后遍历圆的所有 x、y 坐标以计算像素。对于任何颜色为 7(圆圈的颜色)的像素,将像素数加一。最后,您可以使用总像素数作为周长的估计值:
#include <stdio.h>
#include <graph.h>
int
main()
{
unsigned long count;
int x, y;
/* draw a circle */
_setvideomode(_VRES16COLOR); /* 640x480 */
_setcolor(7); /* white */
_ellipse(_GBORDER, 0, 0, 479, 479);
/* count pixels */
count = 0;
for (x = 0; x <= 479; x++) {
for (y = 0; y <= 479; y++) {
if (_getpixel(x, y) == 7) {
count++;
/* highlight the pixel */
_setcolor(15); /* br white */
_setpixel(x, y);
}
else {
/* highlight the pixel */
_setcolor(1); /* blue */
_setpixel(x, y);
}
}
}
/* done */
_setvideomode(_DEFAULTMODE);
printf("pixel count (circumference?) = %lu\n", count);
puts("diameter = 480");
printf("pi = c/d = %f\n", (double) count / 480.0);
return 0;
}
但是通过计算像素来确定周长会低估圆的实际周长。因为 pi 是圆的周长与其直径的比值,所以我的 pi 计算值明显低于 3.14。我尝试了几种视频分辨率,我总是得到大约 2.8 的最终结果:
pixel count (circumference?) = 1356
diameter = 480
pi = c/d = 2.825000
计算像素以估计周长的问题在于像素只是圆形绘图的样本。像素是网格中离散的点,而圆是连续的图。为了更好地估计周长,您必须测量像素之间的距离并将该总测量值用于周长。
要更新程序,您必须编写一个函数来计算任意两个像素之间的距离:x0,y0 和 x,y。您在这里不需要一堆花哨的数学或算法,只需要知道 OpenWatcom_ellipse函数仅以您为圆圈设置的颜色绘制实心像素。该函数不会尝试通过以某种中间颜色绘制附近的像素来提供抗锯齿功能。这可以让你简化数学。在一个圆圈中,像素总是彼此直接相邻:垂直、水平或对角线。
对于垂直或水平相邻的像素,像素“距离”很简单。这是1的距离。
对于对角相邻的像素,您可以使用勾股定理 a²+b²=c² 来计算两个对角像素之间的距离作为2的平方根,或大约1.414。
double
pixel_dist(int x0, int y0, int x, int y)
{
if (((x - x0) == 0) && ((y0 - y) == 1)) {
return 1.0;
}
if (((y0 - y) == 0) && ((x - x0) == 1)) {
return 1.0;
}
/* if ( ((y0-y)==1) && ((x-x0)==1) ) { */
return 1.414;
/* } */
}
我在注释中包含了最后一个“if”语句,这样您就可以看到条件应该代表什么。
要测量周长,我们不需要检查整个圆。我们可以通过只处理左上象限来节省一点时间和精力。这也让我们知道了圆圈中第一个像素的起始坐标;我们将跳过 0,239 处的第一个像素,而是假设它是我们测量四分之一圆周时的第一个 x0,y0 坐标。
(吉姆·霍尔,CC BY-SA 4.0)
最终程序类似于我们的“计算像素”程序,但测量的是圆圈左上象限中像素之间的微小距离。您可能会注意到程序对 y 坐标进行倒计时,从 238 到 0。这适应了四分之一圆中已知起始 x0,y0 坐标为 0,239 的假设。有了这个假设,程序只需要评估 0 到 238 之间的 y 坐标。要估计圆的总周长,请将四分之一测量值乘以 4:
#include <stdio.h>
#include <graph.h>
double
pixel_dist(int x0, int y0, int x, int y)
{
...
}
int
main()
{
double circum;
int x, y;
int x0, y0;
/* draw a circle */
_setvideomode(_VRES16COLOR); /* 640x480 */
_setcolor(7); /* white */
_ellipse(_GBORDER, 0, 0, 479, 479);
/* calculate circumference, use upper left quadrant only */
circum = 0.0;
x0 = 0;
y0 = 479 / 2;
for (x = 0; x <= 479 / 2; x++) {
for (y = (479 / 2) - 1; y >= 0; y--) {
if (_getpixel(x, y) == 7) {
circum += pixel_dist(x0, y0, x, y);
x0 = x;
y0 = y;
/* highlight the pixel */
_setcolor(15); /* br white */
_setpixel(x, y);
}
else {
/* highlight the pixel */
_setcolor(1); /* blue */
_setpixel(x, y);
}
}
}
circum *= 4.0;
/* done */
_setvideomode(_DEFAULTMODE);
printf("circumference = %f\n", circum);
puts("diameter = 480");
printf("pi = c/d = %f\n", circum / 480.0);
return 0;
}
这提供了更好的周长估计。它仍然有一点偏差,因为使用像素测量圆仍然是一个非常粗略的近似值,但最终的 pi 计算更接近 3.14 的预期值:
circumference = 1583.840000
diameter = 480
pi = c/d = 3.299667
文章原文出处:https: //opensource.com/
1678779240
Load and decode the pixels for a PNG or JPEG image in Deno
This module will take the raw data or URL of a PNG or JPEG image and return the decoded pixels and dimensions of the image.
import { getPixels } from "https://deno.land/x/get_pixels/mod.ts";
// From a URL
const { width, height, data } = await getPixels(
"http://placekitten.com/100/100",
);
// From a file
const file = await Deno.readFile("kitten.png");
const { width, height, data } = await getPixels(file);
There is also a getFormat
function that will return the format of the image data. This is detected by the first magic bytes at the start of the data.
import { getFormat } from "https://deno.land/x/get_pixels/mod.ts";
const file = await Deno.readFile("kitten.png");
const format = getFormat(file);
// format === "png"
Author: ascorbic
Source Code: https://github.com/ascorbic/get-pixels
License: MIT licensed
1664861880
A Julia wrapper around MiniFB, a small cross platform library that makes it easy to render 32 bit pixels in a window.
using MiniFB
WIDTH=800
HEIGHT=600
window = mfb_open_ex("My Window", WIDTH, HEIGHT, MiniFB.WF_RESIZABLE)
buffer = zeros(UInt32, WIDTH*HEIGHT)
while true
# TODO add some rendering into the buffer
...
state = mfb_update(window,buffer)
if state != MiniFB.STATE_OK
break
end
end
See the example
directory for usage examples.
Author: Aviks
Source Code: https://github.com/aviks/MiniFB.jl
License: MIT license
1631205995
In this video, we're going to discuss Image Resolution and PPI (Pixels Per Inch) concepts in Computer Graphics. In the display screen, the number of horizontal and vertical pixels is called Resolution and the Image Resolution is specifically concerned with the total number of pixels (Height * Width of Image). Moreover, the Image Resolution is generally described in PPI (Pixels Per Inch). These two are quite important to understand to learn Computer Graphics. So, let's get started now.
00:00 Let's Start
00:30 What is a Pixel?
02:18 Resolution & Its Types
03:29 Image Resolution and PPI
06:08 Representation of PPI
07:49 Use of Calculating PPI with Example
09:07 How to Calculate PPI?
10:33 PPI Calculation Question with Solution
14:52 Closing Notes
#computerscience #computergraphics #pixel #imageresolution
1626272635
Rooting Google Pixel XL permits and give access to various features and updates that aren’t supported by default in your mobile. Why you should root your mobile Google Pixel XL?Would you like to remove the hurdles that come on the way to enjoy the latest updates? If yes then this is for you rooting the mobile allows to reach the level where you control and manage things according to your demand.It makes the software work efficiently.
Follow these Steps to Root Google Pixel XL:
• In the first step you need to download the Fastboot app and then extract it on your PC or laptop.
• Now download the IMG and ZIP these are versions of TWRP recovery.
• IMG version should be saved in the Fastboot folder.
• Simply transfer the ZIP and Magisk ZIP to your phone.You can open the setting and go to > Developer options and turn on both USB debugging and OEM unlocking.
You can connect your mobile with your computer using a USB cable and now Open the Fastboot folder.Simply hold down the Shift key , right-click anywhere and select open command window here.
Just hit enter by typing in the following command.
• Unlock your bootloader and write the following command to reboot your mobile.
• Go to the setting option when your mobile boots back up, and then select the Developer option in the setting and enable USB debugging.Make sure you have connected your Mobile with PC.
• Just type in the following command by replacing or renaming twrp.img with your IMG file name and press the Enter key.
• You can unplug your mobile from your PC and after unplugging tap on Install the TWRP ZIP version and choose Reboot followed by Recovery.
#root #how #google #pixel #xl
1625822630
Today, I’m going to show you a workflow for accurately translating Figma layouts to near-pixel perfect results in the browser. This process involves converting pixel values based on typography and spacing withing Figma, to em and rem units on the frontend.
0:00 - Introduction
0:26 - An Awesome Offer
1:10 - Getting Started
3:30 - Converting Px to Em/Rems
5:29 - Hand over Plugin
15:30 - Is it pixel perfect?
16:33 - Responsive Considerations
18:00 - Closing
Subscribe: https://www.youtube.com/c/DesignCourse/featured
#figma #pixel
1621004407
Why do web developers use the px
unit so blindly? It is just a bad habit? Is it because of a lack of knowledge of other units? Maybe because the design teams rely on px
and pt
for their mocks? It is unclear why the pixel is the current go-to unit for most teams.
Maybe, the main reason is that it looks simple and convenient. Intuitively, we think we understand this unit because it looks as though it is mapping our pixel screen.
The px
unit is something that gets you started very easily, but it turns into a problem later down the road. In this article, I will expose the top three reasons to avoid the pixel unit. We will discuss the problems with its usage and some possible solutions.
Pixel values are no longer based on a hardware pixel. It just wouldn’t work and will look very different for many screens and resolutions. They are instead based on an optical reference unit. So the part that we found more intuitive about that unit is no longer there.
Hardware is changing by the day and pixel densities are growing. We can’t rely on the assumption that devices have a pixel density of 96dpi
. They are no longer a stable point of reference.
Looking at the problem above, why is it happening? Why can’t our layout reach pixel perfection? Because the pixel unit is an absolute one. That means that it is not going to adapt to our browser’s pixel ratio/resolution/size/etc.
Accessibility is a forgotten subject that we all should be paying more attention to. How does the usage of pixel units impact accessibility?
Browsers let you configure your default base font-size
. By default, it is set to 16px
, but it can be easily changed. That is very useful for people with visual impairment. The browser then gives us a hint about the preferred user’s font-size
by setting the base font-size
to that value.
However, if developers use absolute pixel values, that information will be ignored. The base font-size
won’t have any impact on our application layout. The font size will be the same for all users. That is a bad thing since you are ignoring your user’s preferences and hurting your page’s accessibility.
#web-development #css #javascript #pixel
1603044000
Google has released patches addressing high-severity flaws in its System component. The flaws could be remotely exploited to gain access to additional permissions.
Overall, 50 flaws were patched as part of Google’s October security update for the Android operating system, released on Monday. As part of this, Qualcomm, whose chips are used in Android devices, patched a mix of high- and critical-severity vulnerabilities tied to 22 CVEs.
Two elevation of privilege (EoP) issues, the most serious of the flaws, exist in the Android System component, the core of the operating system that’s on Android phones. These are two vulnerabilities (CVE-2020-0215 and CVE-2020-0416) that can be exploited remotely by an attacker using a specially crafted transmission. The flaws are fixed in Android versions 8.0, 8.1, 9, 10 and 11.
Also fixed in System are eight high-severity information-disclosure flaws (CVE-2020-0377, CVE-2020-0378, CVE-2020-0398, CVE-2020-0400, CVE-2020-0410, CVE-2020-0413, CVE-2020-0415 and CVE-2020-0422).
Three high-severity flaws also exist in the Media Framework (which offers support for playing a variety of common media types, so users can easily utilize audio, video and images). The three (CVE-2020-0213, CVE-2020-0411, CVE-2020-0414) could lead to remote information disclosure with no additional execution privileges needed.
Google also fixed five high-severity flaws in the Framework component, which is a set of APIs (consisting of system tools and user interface design tools) that allow developers to quickly and easily write apps for Android phones. These include two EoP flaws (CVE-2020-0420 and CVE-2020-0421), which enable a local malicious application to bypass user-interaction requirements in order to gain access to additional permissions. Three information-disclosure flaws (CVE-2020-0246, CVE-2020-0412, CVE-2020-0419) were also fixed.
Finally, Google fixed a high-severity EoP flaw (CVE-2020-0408) in Android runtime, the application runtime environment used by the Android OS. The vulnerability, which could enable a local attacker to execute arbitrary code within the context of an application that uses the library, was fixed in versions 8.0, 8.1, 9, 10 and 11.
Google also rolled out patches for flaws in various third-party components in its Android ecosystem. One such flaw (CVE-2020-0423) exists in the kernel, which could enable a local attacker using a specially crafted file to execute arbitrary code within the context of a privileged process. Also fixed were several MediaTek components, including ones affecting the keyinstall, widevine and ISP components.
Finally, 22 critical and high-severity flaws were addressed in Qualcomm components, including four high-severity flaws in the kernel component (CVE-2020-11125, CVE-2020-11162, CVE-2020-11173, CVE-2020-11174) and six critical flaws (CVE-2020-3654, CVE-2020-3657, CVE-2020-3673, CVE-2020-3692, CVE-2020-11154 and CVE-2020-11155) in “closed-source components.”
#vulnerabilities #web security #(cve-2020-0215 #android #android security update #cve-2020-0416 #elevation of privilege #framework #google #information disclosure #kernel #media framework #october 2020 #pixel #qualcomm #samsung
1600592400
Let’s create a web component based on a hardware device!
** NOTE: I originally published this post to the Wokwi’s official blog.
In the following post, I will describe my personal experience in making a web component based on a hardware device, as part of contributing to “Wokwi-elements”. It’s an extremely cool open source library for “Arduino elements” made by Uri Shaked.
The creativity behind the Wokwi lib immediately caught my mind and I recognised an opportunity to play with new techniques and gain more experience with concepts I was experienced with.
#web-components #canvas #pixel #web-development #svg
1592703060
Designing for developers. Some might say the two are a different breed, but in my experience there is one thing we will always have in common – the hunger for perfection. Sometimes we may see perfection in a different light, or even at the total opposite ends of the spectrum. However, ultimately, we usually share the same goals – to create something great, change people’s lives and make the world a better place.
#pixel